Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: How to stop start-job?

Tags:

powershell

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.

like image 409
Fomovet Avatar asked Dec 22 '25 00:12

Fomovet


2 Answers

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
like image 197
js2010 Avatar answered Dec 25 '25 06:12

js2010


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.
like image 44
mklement0 Avatar answered Dec 25 '25 08:12

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!