alejandro5042 February 2016

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

Answers


PetSerAl February 2016

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


Mathias R. Jessen February 2016

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

Post Status

Asked in February 2016
Viewed 2,074 times
Voted 4
Answered 2 times

Search




Leave an answer