Friday, April 28, 2017

Watching for new processes with PowerShell

Suppose you want a PowerShell script to watch for new processes and do something when one starts. You can do something like this:

$query = New-Object System.Management.WqlEventQuery ("__InstanceCreationEvent", (New-Object TimeSpan (0, 0, 1)), 'TargetInstance isa "Win32_Process"')
$watcher = New-Object System.Management.ManagementEventWatcher
$watcher.Query = $query
$watcher.Options.Timeout = [System.Management.ManagementOptions]::InfiniteTimeout
While ($true) {
    $evt = $watcher.WaitForNextEvent()
    # Do something about $evt
}

That script uses WMI to monitor for the creation of new process objects, with a timer resolution of one second, so you'll see all processes that live longer than a second. You can use the TargetInstance property on $evt to get information on the actual process.

No comments:

Post a Comment