Powershell在后台运行批处理文件,继续执行,然后等待批处理文件完成

时间:2015-01-30 14:38:47

标签: powershell batch-file cmd background-process

我有一个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脚本窗口中,并知道批处理文件何时完成。

3 个答案:

答案 0 :(得分:1)

只要您正确检查作业状态,这应该有效:

$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

答案 1 :(得分:1)

start-job仅存在于3.0之后的Powershell版本中,因此请确保安装了正确的版本。

答案 2 :(得分:0)

您需要在Start-SleepStart-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
}