获取外部进程退出代码时的PowerShell 3.0行为

时间:2013-11-22 19:25:24

标签: powershell

我一直在使用此网站上其他帖子的代码:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
**$p.Start() | Out-Null**
#Do Other Stuff Here....
**$p.WaitForExit()**
$p.ExitCode

它在PowerShell 2.0下运行良好。服务器已升级到PowerShell 3.0,现在两个大胆的内容失败了:

Exception calling "Start" with "0" argument(s): "The system cannot find the
file specified"
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:126 char:1
+ $p.Start() | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : Win32Exception

Exception calling "WaitForExit" with "0" argument(s): "No process is
associated with this object."
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:128 char:1
+ $p.WaitForExit()
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

为什么它会破坏,我该如何纠正它以便它适用于版本2.0和3.0?

2 个答案:

答案 0 :(得分:2)

嗯,我不能在我的V3系统上重现错误。但是,当你可以使用Start-Process命令执行此操作时,为什么要解决所有这些问题,例如:

$p = Start-Process Notepad -Wait -PassThru
$p.ExitCode

答案 1 :(得分:1)

您可能想尝试提供notepad.exe的完全限定路径,例如“C:\ Windows \ notepad.exe”。