≡ Menu

PowerShell: Track process stop/termination

I showed you how to track process startup using PowerShell in my previous post. Now let us see how to track the process stop or termination using PowerShell.

PowerShell: How to track process startup/new processes

The approach we use for tracking process stop is similar to process startup where we rely on querying WMI class for process termination events. We need to query __InstanceDeletionEvent  WMI class to get details when a process is terminated. The process object returned via $event.SourceEventArgs.NewEvent.TargetInstance is not having process termination date time. I couldn’t find any other way to fetch process termination time so I decided to reduce the polling interval to 2 seconds so that I can rely on event generation time to get nearest value to actual termination time. So when you see the time of termination, expect it to be anywhere within last 2 seconds.

Code:

function Enable-ProcessStopTrace {            
[CmdLetBinding()]            
param(            
)             
$Query = "Select * From __InstanceDeletionEvent within 2 Where TargetInstance ISA 'Win32_Process'"            
$Identifier = "StopProcess"            
$ActionBlock = {            
 $e = $event.SourceEventArgs.NewEvent.TargetInstance            
 write-host ("Process {0} with PID {1} has stopped at {2}" -f $e.Name, $e.ProcessID, $event.TimeGenerated)            
}            
Register-WMIEvent -Query $Query -SourceIdentifier $Identifier -Action $ActionBlock            
            
            
}

Output:

enable-processstoptrace

Happy learning..

Comments on this entry are closed.