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

前端 未结 4 791
无人共我
无人共我 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:03

    If found that using Invoke-Command was able to bypass the restriction that the background job dies with it's parent. The nice thing is that the syntax is almost the same as with start-job, so the scriptblock can be kept as is.

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

    would just turn into

    Invoke-Command -ComputerName . -AsJob -scriptblock { sleep 10; cmd /c set > c:\env.txt; }
    

    and suddenly survive the death of it's parent (probably because invoke-command is fit to run programs on another computer so the parent can never matter to it)

提交回复
热议问题