Reputation: 26382
If I use powershell to run an external command, how do I obtain it's pid?
I'd like to obtain it for purposes of gracefully exiting it later (not just straight up killing the process, but rather doing it in more the sense of a finally
block)
Upvotes: 1
Views: 2267
Reputation: 17161
Get-Process
Write-Output (Get-Process -Name "Sonos").Id
That will get you the PID - however based on what you're describing it's easier to the output of Get-Process
to a variable and deal with the object instead
try {
$process = Start-Process -FilePath "C:\Program Files (x86)\Sonos\Sonos.exe"
Write-Output $process.Id
}
catch {
throw
}
finally {
if ($process) {
Stop-Process -InputObject $process
# Alternative: $process | Stop-Process
}
}
Upvotes: 1
Reputation: 17719
Using System.Diagnostics.Process object, you can start a process, and return a Process object, which includes the newly created process PID.
For example:
$Process = [Diagnostics.Process]::Start("nssm.exe")
Write-Host $Process.Id
Upvotes: 1