Consider the following code:
start-job -scriptblock { sleep 10; cmd /c set > c:\env.txt; } exit
The background job is killed when the parent exits, so the call to cmd.exe never occurs. I would like to write some similar code, such that the parent exits immediately, and the child continues to run in the background.
I would like to keep everything in one script if possible.
The Start-Job cmdlet starts a PowerShell background job on the local computer. A PowerShell background job runs a command without interacting with the current session. When you start a background job, a job object returns immediately, even if the job takes an extended time to finish.
PowerShell has four types of jobs – Background Jobs, Remote Jobs,WMI Jobs and Scheduled Jobs.
The following command starts a job object and saves the resulting job object in the $job variable. Beginning in PowerShell 6.0, you can use the background operator ( & ) at the end of a pipeline to start a background job.
The Get-Job cmdlet gets objects that represent the background jobs that were started in the current session. You can use Get-Job to get jobs that were started by using the Start-Job cmdlet, or by using the AsJob parameter of any cmdlet. Without parameters, a Get-Job command gets all jobs in the current session.
You will have to start a process:
start-process powershell -ArgumentList "sleep 10; cmd /c set > c:\env.txt" -WindowStyle hidden
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With