Fomovet
Fomovet

Reputation: 323

Powershell: How to stop start-job?

I have the following job in powershell:

$DoIt = '...'
....
 If ([IntPtr]::size -eq 8) {
        start-job { 
        param($a) IEX $a 
        } -RunAs32 -Argument $DoIt | wait-job | Receive-Job
        Get-Job | Stop-Job
        Exit
        Write-Host "exit powershell" -NoNewLine -ForegroundColor Green
}   
else {
    IEX $DoIt
}

simply put, how to stop or close powershell after executing the start-job function. What should I do?Tried some ways to find that it didn't work.

Upvotes: 2

Views: 5524

Answers (2)

mklement0
mklement0

Reputation: 438763

how to stop or close powershell after executing the start-job function.

  • If you exit your session before the background job launched with Start-Job has completed, you'll stop (abort) it implicitly, because PowerShell cleans up pending background jobs automatically when the session that created them exits.

    • Therefore, if you want to launch a background operation that keeps running when the session that initiated it exits, you'll have to use a different mechanism, such as Start-Process -WindowStyle Hidden ... (Windows-only).
  • To wait for the background job to finish, use Wait-Job or - combined with retrieving its output - Receive-Job -Wait.

    • Note that this is only useful if you perform other actions in between starting the background job and waiting for its completion - otherwise, you could just run the operations directly, without the need for a background job.

Upvotes: 3

js2010
js2010

Reputation: 27491

Remove-Job. Here's an example. If the job completes, you don't have to run stop-job. Although invoke-expression is almost always the wrong answer, and you have to watch user input to it. I'm in osx.

PS /Users/js> $job = start-job { param($a) sleep $a } -Args 3600
PS /Users/js> get-job

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
11     Job11           BackgroundJob   Running       True            localhost             param($a) sleep $a

PS /Users/js> stop-job $job
PS /Users/js> remove-job $job  # or just remove-job -force
PS /Users/js> get-job  # none

Upvotes: 5

Related Questions