启动过程后作业的脚本块中的代码不执行 [英] Code in Job's Script Block after Start-Process Does not Execute

查看:55
本文介绍了启动过程后作业的脚本块中的代码不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用PowerShell 5.1创建自动化脚本时,遇到一个问题–在作业的脚本块中,启动过程之后的代码将无法执行.这是一个简单的复制程序:

When I create a automation script with PowerShell 5.1, I got an issue – in a script block of a job, the code after Start-Process will not get chance to execute. Here’s a simple repro:

步骤1 >>为启动过程准备一个.cmd文件,callee.cmd中的代码为:

@echo off
echo "Callee is executing ..."
exit /B 0

步骤2 >>准备PowerShell代码

$scriptBlock = {
    $res = Start-Process -FilePath "cmd.exe" -Wait -PassThru -NoNewWindow -ArgumentList "/c .\callee.cmd"
    throw "ERROR!"
}

$job = Start-Job -ScriptBlock $scriptBlock
Wait-Job $job
Receive-Job $job
Write-Host($job.State)

步骤3 >>运行PowerShell脚本,屏幕上的输出为:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Completed     True            localhost            ...
Completed

期望值应为失败". 我的代码有问题还是我以错误的方式使用作业?

The expected value should be "Failed". Does my code have problem or I’m using jobs in a wrong way?

推荐答案

Start-Job在单独的PowerShell进程中以所谓的服务器模式运行作业.在这种模式下,PowerShell作业流程使用标准的输入和输出流与父流程交换消息.

Start-Job run job in separate PowerShell process in so-called server mode. In this mode PowerShell job process use standard input and output streams to exchange messages with the parent process.

-NoNewWindow参数指示它将生成的控制台子进程连接到其父级的标准流.

-NoNewWindow parameter of Start-Process cmdlet instruct it to connect spawned console child process to the standard streams of its parent.

因此,使用PowerShell作业内部的Start-Process -NoNewWindow,将生成的cmd.exe进程连接到相同的流,PowerShell作业进程使用该流与自己的父进程交换消息.

Thus, using Start-Process -NoNewWindow inside of PowerShell job, you connect spawned cmd.exe process to the same streams, which PowerShell job process use to exchange messages with its own parent process.

现在,生成cmd.exe到其标准输出流中时,它会扰乱PowerShell作业进程与其父进程之间的正常消息交换,从而导致某些意外行为.

Now, when spawned cmd.exe write something into its standard output stream, it disturb normal message exchange between PowerShell job process and its parent, which leads to some unexpected behavior.

这篇关于启动过程后作业的脚本块中的代码不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆