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

前端 未结 4 786
无人共我
无人共我 2020-12-09 16:17

Consider the following code:

start-job -scriptblock { sleep 10; cmd /c set > c:\\env.txt; }
exit

The background job is killed when the p

4条回答
  •  隐瞒了意图╮
    2020-12-09 17:13

    You can also do it like that

    $a = start-job -scriptblock { sleep 10; cmd /c set > c:\env.txt; }
    Register-ObjectEvent -InputObject $a -EventName StateChanged -SourceIdentifier "finished"
    $b = Wait-Event -SourceIdentifier "finished"
    exit
    

    Your script will wait for the end of the scriptblock to finish.

提交回复
热议问题