我有一个PowerShell脚本,用于设置开发环境。在此过程中,它会调用几个批处理文件。
我希望powershell脚本继续处理,直到它到达脚本中需要批处理文件完成的位置。
简单的测试批处理文件“md.cmd”
@echo Create directory
md testDirectory
PowerShell脚本
$job1 = Start-Job {d:\test\md.cmd}
# run some scripts
while($job1.state -eq "Running")
{
# wait for batch files to end
}
# run some more script using what the batch file did
这个问题是我无法使用Start-Job
执行批处理文件。
如何将批处理文件作为后台进程或甚至在新的命令窗口中执行,将焦点保持在powershell脚本窗口中并知道批处理文件何时完成。
只要您正确检查作业状态,这应该有效:
$job1 = Start-Job {cmd /c d:\test\md.cmd}
#run some scripts
while($job1.state -eq "Running")
{
#wait for batch files to end
}
#run some more script using what the batch file did
start-job仅存在于3.0之后的Powershell版本中,因此请确保安装了正确的版本。
您需要在Start-Sleep
和Start-Job
之间添加while loop
以避免此错误,因为在您的代码的情况下,需要一秒钟的时间来更新作业的状态,当while循环已经运行时。这导致$job1.state
仍显示“空闲”,因此这将永远不会进入while循环。
$job1 = Start-Job {cmd /c d:\test\md.cmd}
Start-Sleep 5 # to give time to update job status
# run some scripts
while($job1.state -eq "Running")
{
# wait for batch files to end
}