如何在Powershell中开始一个比其父母更长的后台工作?

ngo*_*eff 17 powershell

请考虑以下代码:

start-job -scriptblock { sleep 10; cmd /c set > c:\env.txt; }
exit
Run Code Online (Sandbox Code Playgroud)

父进程退出后,后台作业将被终止,因此不会发生对cmd.exe的调用.我想写一些类似的代码,这样父母就会立即退出,孩子继续在后台运行.

如果可能的话,我想将所有内容保存在一个脚本中.

man*_*lds 14

你必须开始一个过程:

start-process powershell -ArgumentList "sleep 10; cmd /c set > c:\env.txt" -WindowStyle hidden
Run Code Online (Sandbox Code Playgroud)


小智 7

如果使用Start-Process,则会创建一个新的子进程,该进程将Powershell会话作为其父进程。如果您杀死启动该进程的Powershell父进程,则新进程将被孤立并继续运行。但是,如果您杀死父进程进程树,它将无法生存

Start-Process -FilePath notepad.exe
Run Code Online (Sandbox Code Playgroud)

Powershell无法为您在进程树之外启动新的独立进程。但是,这可以在Windows中使用CreateProcess完成,并且此功能通过WMI公开。幸运的是,您可以从powershell调用它:

Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList notepad.exe
Run Code Online (Sandbox Code Playgroud)

这样,如果进程树被杀死,新进程也将继续运行,因为新进程没有将Powershell会话作为父进程,而是将WMI主机进程作为父进程。