从PowerShell启动一个无人参与的进程

ale*_*042 1 powershell process

默认情况下,从PowerShell启动进程时,它会附加到其父(shell).如果您终止进程树,这些进程也会死掉.我想启动一个shell的对等进程; 又名.当我杀死PowerShell树时,我不希望它死掉.

$spotifyProcess = start Spotify.exe -PassThru

$spotifyParentId = (gwmi win32_process -Filter "processid='$($spotifyProcess.Id)'").ParentProcessId
$shellId = [System.Diagnostics.Process]::GetCurrentProcess().Id

if ($spotifyParentId -eq $shellId)
{
    throw 'Not what I want!!'
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 6

由于 Windows 中进程树的简单性质(只是每个进程祖先的向后链接列表),一个“经典”技巧是打开一个单独的进程,然后该进程依次启动新的“独立”进程。

powershell.exe非常简单:

powershell.exe -Command 'Start-Process notepad.exe'
Run Code Online (Sandbox Code Playgroud)

“内部”powershell.exe实例启动notepad.exe,并立即退出,留下notepad.exe孤立的实例


use*_*407 5

您可以使用WMI类的Create方法Win32_Process.有几种方法可以在PowerShell中调用它:

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

([WmiClass]'Win32_Process').Create('notepad')
Run Code Online (Sandbox Code Playgroud)

V3 +:

Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='notepad'}
Run Code Online (Sandbox Code Playgroud)