如何告诉PowerShell在开始下一个命令之前等待每个命令结束?

时间:2009-11-16 11:04:43

标签: powershell wait execution

我有一个PowerShell 1.0脚本来打开一堆应用程序。第一个是虚拟机,其他是开发应用程序。我希望虚拟机在其他应用程序打开之前完成启动。

在bash中我可以说"cmd1 && cmd2"

这就是我所拥有的......

C:\Applications\VirtualBox\vboxmanage startvm superdooper
    &"C:\Applications\NetBeans 6.5\bin\netbeans.exe"

8 个答案:

答案 0 :(得分:312)

通常,对于内部命令,PowerShell会在开始下一个命令之前等待。此规则的一个例外是基于外部Windows子系统的EXE。第一个技巧是如此管道到Out-Null

Notepad.exe | Out-Null

PowerShell将一直等到Notepad.exe进程退出,然后再继续。从阅读代码中获取这一点很精致但有点微妙。您还可以使用-Wait参数启动进程:

Start-Process <path to exe> -NoNewWindow -Wait

如果您使用的是PowerShell社区扩展版,则为:

$proc = Start-Process <path to exe> -NoWindow
$proc.WaitForExit()

PowerShell 2.0中的另一个选项是使用后台作业:

$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job

答案 1 :(得分:44)

除了使用Start-Process -Wait之外,管道输出可执行文件将使Powershell等待。根据需要,我通常会选择Out-NullOut-DefaultOut-StringOut-String -StreamHere是一些其他输出选项的长列表。

# Saving output as a string to a variable.
$output = ping.exe example.com | Out-String

# Filtering the output.
ping stackoverflow.com | where { $_ -match '^reply' }

# Using Start-Process affords the most control.
Start-Process -Wait SomeExecutable.com

我确实错过了您引用的CMD / Bash样式运算符(&amp;,&amp;&amp;,||)。它 似乎我们必须more verbose with Powershell

答案 2 :(得分:11)

只需使用&#34;等待过程&#34; :

"notepad","calc","wmplayer" | ForEach-Object {Start-Process $_} | Wait-Process ;dir

工作完成

答案 3 :(得分:6)

如果您使用Start-Process <path to exe> -NoNewWindow -Wait

您还可以使用-PassThru选项来回显输出。

答案 4 :(得分:5)

某些程序无法很好地处理输出流,使用管道Out-Null可能无法阻止它 并且Start-Process需要-ArgumentList开关来传递参数,不太方便 还有另一种方法。

$exitCode = [Diagnostics.Process]::Start(<process>,<arguments>).WaitForExit(<timeout>)

答案 5 :(得分:2)

包含选项-NoNewWindow会给我一个错误:Start-Process : This command cannot be executed due to the error: Access is denied.

我能让它发挥作用的唯一方法就是打电话:

Start-Process <path to exe> -Wait

答案 6 :(得分:0)

进一步研究你甚至可以动态解析

e.g。

& "my.exe" | %{
    if ($_ -match 'OK')
    { Write-Host $_ -f Green }
    else if ($_ -match 'FAIL|ERROR')
    { Write-Host $_ -f Red }
    else 
    { Write-Host $_ }
}

答案 7 :(得分:0)

总是有cmd。如果您在引用启动过程的参数时遇到麻烦,可能会不太烦人:

cmd /c start /wait notepad