如何让PowerShell在开始下一个之前等待每个命令结束?
我有一个PowerShell 1.0脚本来打开一堆应用程序。 第一个是虚拟机,其他的是开发应用程序。 我希望虚拟机在其他应用程序打开之前完成引导。
在bash中,我只能说"cmd1 && cmd2" 
这是我的…
 C:\Applications\VirtualBox\vboxmanage startvm superdooper &"C:\Applications\NetBeans 6.5\bin\netbeans.exe" 
	
 通常,对于PowerShell在启动下一个命令之前等待的内部命令。 此规则的一个例外是基于外部Windows子系统的EXE。 第一个诀窍就是像下面这样通过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 ,pipe道可执行文件的输出将使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做更详细的介绍 。
只需使用“等待进程”即可
 "notepad","calc","wmplayer" | ForEach-Object {Start-Process $_} | Wait-Process ;dir 
工作完成了
 如果使用Start-Process <path to exe> -NoNewWindow -Wait 
 您也可以使用-PassThru选项-PassThru输出。 
 有些程序不能很好地处理输出stream,使用pipe道Out-Null可能不会阻塞它。 
 而Start-Process需要-ArgumentList开关来传递参数,不太方便。 
 还有另一种方法。 
 $exitCode = [Diagnostics.Process]::Start(<process>,<arguments>).WaitForExit(<timeout>) 
 包括选项-NoNewWindow给了我一个错误: Start-Process : This command cannot be executed due to the error: Access is denied. 
我能做到的唯一方法就是打电话给:
 Start-Process <path to exe> -Wait