≡ Menu

PSTip# Start a process and get its PID using Powershell

In today’s PSTIP# section will show you how to start a new process and get its PID using powershell. Sometimes we may get requirement to kill the process we started and in such cases knowing the PID will help us in easily killing the process. Unfortunately, Start-Process cmdlet in Powershell will not return the PID of the process after starting it. So we need to depend on [Diagnostics.Process] dotnet class for this purpose.

Code:

$Process = [Diagnostics.Process]::Start("notepad")            
$id = $Process.Id            
Write-Host "Process created. Process id is $id"            
Write-Host "sleeping for 5 seconds"            
Start-Sleep -Seconds 5            
try {            
    Stop-Process -Id $id -ErrorAction stop            
    Write-Host "Successfully killed the process with ID: $ID"            
} catch {            
    Write-Host "Failed to kill the process"            
}

Hope this helps.

{ 1 comment… add one }
  • William January 25, 2017, 7:26 pm

    Thanks. This was very helpful!

Leave a Comment