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

前端 未结 4 772
无人共我
无人共我 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 16:53

    If you use Start-Process, you create a new child process that has your powershell session as its parent process. If you kill the powershell parent process that starts this, the new process will be orphaned and keep running. It will, however, not survive if you kill the parent's process tree

    Start-Process -FilePath notepad.exe
    

    Powershell cannot start a new independent process outside of its process tree for you. However, this can be done in Windows using CreateProcess and this functionality is exposed through WMI. Luckily, you can call that from powershell:

    Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList notepad.exe
    

    This way, the new process will also keep running if the process tree is killed, because the new process does not have your powershell session as a parent, but the WMI host process.

提交回复
热议问题