# 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](/red-teaming/notes/powershell/powershell-snippets/query-powershell-alternative-hosts-with-wmi.md) and [Alternate PowerShell Hosts](/red-teaming/notes/powershell/alternate-powershell-hosts.md).

```powershell
$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:

* [WMI - Windows Management Instrumentation](/red-teaming/notes/powershell/wmi-windows-management-instrumentation.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://otter.gitbook.io/red-teaming/notes/powershell/powershell-snippets/monitor-powershell-hosts-with-wmi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
