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

问题描述 投票:1回答:3

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

powershell batch-file cmd background-process
3个回答
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
投票

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


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
}
© www.soinside.com 2019 - 2024. All rights reserved.