我创建了一个执行以下操作的测试可执行文件
Console.WriteLine("In Exe start" + System.DateTime.Now);
System.Threading.Thread.Sleep(5000);
Console.WriteLine("In Exe end" + System.DateTime.Now);
然后编写了这个powershell脚本,它按预期等待exe完成运行,然后输出文本“ps1结束”和时间
push-location "C:\SRC\PowerShell-Wait-For-Exe\bin\Debug";
$exe = "PowerShell-Wait-For-Exe.exe"
$proc = (Start-Process $exe -PassThru)
$proc | Wait-Process
Write-Host "end of ps1" + (Get-Date).DateTime
下面的 powershell 也正确地等待 exe 完成。
$check = Start-Process $exe $AllArgs -Wait -Verb runas
Write-Host "end of ps1" + (Get-Date).DateTime
添加 WaitForExit 调用给了我这个错误。
You cannot call a method on a null-valued expression.
At line:2 char:1
+ $check.WaitForExit()
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
然而这确实有效
$p = New-Object System.Diagnostics.Process
$pinfo = New-Object System.Diagnostics.ProcessStartInfo("C:\PowerShell-Wait-For-Exe\bin\Debug\PowerShell-Wait-For-Exe.exe","");
$p.StartInfo = $pinfo;
$p.Start();
$p.WaitForExit();
Write-Host "end of ps1" + (Get-Date).DateTime
我想您可能将 Start-Process powershell 命令与 .NET 框架 Process 对象混淆了