内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我有一个 PowerShell 1.0 脚本, 只是打开了一大堆应用程序。第一个是虚拟机, 其他是开发应用程序。我希望虚拟机在其他应用程序打开之前完成启动。
可以说"cmd1 && cmd2"
C:\Applications\VirtualBox\vboxmanage startvm superdooper &"C:\Applications\NetBeans 6.5\bin\netbeans.exe"
通常,对于内部命令,PowerShell在启动下一个命令之前会等待。此规则的一个例外是基于EXE的外部Windows子系统。第一个窍门是将管道输送到Out-Null
就像这样:
Notepad.exe | Out-Null
Powershell将等到Notepad.exe进程退出后再继续。这是很好的,但从阅读代码中学到了一些微妙的东西。可以使用Start-Process和-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
除了使用Start-Process -Wait
,管道化可执行文件的输出将使Powershell等待。根据需要,我通常会用管道传送到Out-Null
,Out-Default
,Out-String
或Out-String -Stream
.是其他一些输出选项的长列表。
# 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样式操作符(&,&&,)。