Process Tracking in Windows environment is tough in general sense. That means, it is difficult to track when a process is started, what are the command line arguments it got, what is the path of executable, Process ID and several other parameters. This kind of facility helps in cases when you are troubleshooting a problem or you want to know who is starting a process on a server. I got similar requirement and figured out that it can be done easily with PowerShell.
PowerShell has a cmdlet called Register-WmiEvent which can be used for configuring events. We can use this cmdlet to configure monitoring around the process creation and we can log several details like when the process is started, what are the arguments, who started it etc. The approach I am going to use below relies on WMI event capabilities. It is much better approach that constantly scanning the current list of processes to know when a process is started. Also it is difficult to track the processes which live for very short interval. The WMI eventing capabilities addresses such problems easily and we can keep a watch on all processes that are starting.
Code
function Enable-ProcessTrace { [CmdLetBinding()] param( ) $Query = "Select * From __InstanceCreationEvent within 3 Where TargetInstance ISA 'Win32_Process'" $Identifier = "StartProcess" $ActionBlock = { $e = $event.SourceEventArgs.NewEvent.TargetInstance write-host ("Process {0} with PID {1} has started" -f $e.Name, $e.ProcessID) } Register-WMIEvent -Query $Query -SourceIdentifier $Identifier -Action $ActionBlock }
As you can see in the above code, I am querying _InstanceCreationEvent WMI class for any new instances of Win32_Process class every 3 seconds. When any process started, the code in the Action block will be executed. We can leverage this facility perform any actions based on process start.
The query string is based on WQL where ISA and WITHIN are keywords. The $event contains the information about the process that started. To see process details you can access the properties of $event.SourceEventArgs.NewEvent.TargetInstance object. Modify the contents of action block to suite your needs.
Usage:
Copy & paste the above code in PowerShell window and call the function like below.
Output:
You need to keep the powershell window opened so that you can see messages like below when a process is started.
Happy learning…
You can find details similar code for tracking process top at below link
PowerShell: Track process stop/termination