Monitor PowerShell hosts with WMI

This snippet alerts whenever a PowerShell host process is started; the detection technique is the same one discussed in Query PowerShell alternative hosts with WMI and Alternate PowerShell Hosts.

$EventName = 'PowerShellHostProcessWatcher'

Register-CimIndicationEvent -Query "SELECT FileName, ProcessID FROM Win32_ModuleLoadTrace WHERE FileName LIKE '%System.Management.Automation%'" -Action {

    Write-Host @"
PowerShell host process loaded!
Process ID: $($EventArgs.NewEvent.ProcessID)
File path:  $($EventArgs.NewEvent.FileName)
"@

    Unregister-Event -SourceIdentifier $EventSubscriber.SourceIdentifier
} -SourceIdentifier $EventName

References:

Last updated