The code in the Script task. The block does not execute after the start-up process.

When I create a script automation using PowerShell 5.1, I had a problem - in the script job block, the code after the start-up process will not have a chance of execution. Heres a simple reproduction:

Step 1 → Prepare the .cmd file for the Start-Process, the code in callee.cmd:

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

Step 2 -> Prepare PowerShell Code,

 $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) 

Step 3 -> Run the PowerShell script, the output on the screen:

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

The expected value should be "Failed". Does my code have problems or Im using jobs in the wrong way?

+2
source share
1 answer

Start-Job execute the task in a separate PowerShell process in the so-called server mode. In this mode of operation, PowerShell uses standard input and output streams to exchange messages with the parent process.

-NoNewWindow parameter of the Start-Process cmdlet indicates that it connects the child process of the spawned console to its parent's standard threads.

Thus, using the Start-Process -NoNewWindow inside a PowerShell job, you connect the generated cmd.exe process to the same thread that uses the PowerShell process to exchange messages with its own parent process.

Now that the generated cmd.exe writes something to its standard output stream, it disrupts the normal messaging between the PowerShell job process and its parent, which leads to unexpected behavior.

+1
source

Source: https://habr.com/ru/post/972069/


All Articles