alejandro5042
alejandro5042

Reputation: 851

Launch an unparented process from PowerShell

By default, when you launch a process from PowerShell, it is attached to its parent (the shell). If you kill the process tree, these processes also die. I would like to launch a process that is a peer to the shell; aka. when I kill the PowerShell tree, I don't want it to die.

$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!!'
}

Upvotes: 4

Views: 3253

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

A "classic" trick, due to the simple nature of a Process Tree in Windows (just a backwards linked list to each process' ancestor), is to open a separate process that then in turn launches your new "independent" process.

In powershell.exe this is super easy:

powershell.exe -Command 'Start-Process notepad.exe'

The "inner" powershell.exe instance launches notepad.exe, and exits immediately, leaving notepad.exe orphaned

Upvotes: 6

user4003407
user4003407

Reputation: 22122

You can use Create method of Win32_Process WMI class. There are several ways to call it in PowerShell:

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

([WmiClass]'Win32_Process').Create('notepad')

v3+:

Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='notepad'}

Upvotes: 7

Related Questions