如何告诉PowerShell在开始下一个命令之前等待每个命令结束?
如何告诉PowerShell在开始下一个命令之前等待每个命令结束?
我有一份PowerShell 1.0脚本,只是用来打开一堆应用程序。第一个是虚拟机,其他的是开发应用程序。 我希望在打开其余的应用程序之前,虚拟机可以完成引导。
在bash中,我只需说\"cmd1 && cmd2\"
这就是我得到的...
C:\Applications\VirtualBox\vboxmanage startvm superdooper &"C:\Applications\NetBeans 6.5\bin\netbeans.exe"
admin 更改状态以发布 2023年5月21日
除了使用 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 风格的操作符(&、&&、||)。看起来我们必须在 Powershell 中写得更加详细了。
通常情况下,对于内部命令,PowerShell在启动下一条命令之前会等待一会儿。这个规则的一个例外是外部基于Windows子系统的EXE文件。第一个技巧是像这样使用管道 Out-Null
:
Notepad.exe | Out-Null
PowerShell会等待Notepad.exe进程退出后才继续。这很好,但从代码中读取这一点有点微妙。你还可以使用Start-Process
,并带上-Wait
参数:
Start-Process-NoNewWindow -Wait
如果你使用的是PowerShell社区扩展版本,可以使用:
$proc = Start-Process-NoNewWindow -PassThru $proc.WaitForExit()
PowerShell 2.0中的另一种选项是使用后台作业:
$job = Start-Job { invoke command here } Wait-Job $job Receive-Job $job