Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I start a background job in Powershell that outlives it's parent?

Tags:

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.

like image 279
ngoozeff Avatar asked Dec 15 '11 05:12

ngoozeff


People also ask

How do I run a program in the background in PowerShell?

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.

What are the different types of background jobs in PowerShell?

PowerShell has four types of jobs – Background Jobs, Remote Jobs,WMI Jobs and Scheduled Jobs.

What can you use to start a job in PowerShell other than the start-job command?

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.

How do I get all background jobs in the current session in PowerShell?

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.


Video Answer


1 Answers

You will have to start a process:

start-process powershell -ArgumentList "sleep 10; cmd /c set > c:\env.txt" -WindowStyle hidden 
like image 71
manojlds Avatar answered Sep 25 '22 19:09

manojlds