- 1 year ago
Listen for WMI Event of a new process created in powershell while using ApplicationContext
To listen for a WMI event of a new process created in PowerShell while using an ApplicationContext, you can utilize the Register-WmiEvent
cmdlet along with a script block to handle the event. Here's an example:
powershellAdd-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Windows.Forms;
public class CustomApplicationContext : ApplicationContext
{
private ManagementEventWatcher eventWatcher;
public CustomApplicationContext()
{
// Create a WMI event query for process creation
string query = "SELECT * FROM Win32_ProcessStartTrace";
// Create the event watcher
eventWatcher = new ManagementEventWatcher(new WqlEventQuery(query));
eventWatcher.EventArrived += EventWatcher_EventArrived;
eventWatcher.Start();
}
private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
// Handle the new process event
PropertyDataCollection properties = e.NewEvent.Properties;
string processName = properties["ProcessName"].Value.ToString();
int processId = Convert.ToInt32(properties["ProcessID"].Value);
// Do something with the process information
MessageBox.Show($"New process created:\n\nName: {processName}\nID: {processId}");
}
}
// Create and run the application context
$context = New-Object CustomApplicationContext
[void][System.Windows.Forms.Application]::Run($context)
"@
# Start the PowerShell host with the script block
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command {
# Run the script block containing the CustomApplicationContext
}
In this example, we define a CustomApplicationContext
class that derives from ApplicationContext
and handles the WMI event for new process creation. Within the CustomApplicationContext
constructor, we create a ManagementEventWatcher
and register an event handler for the EventArrived
event.
When a new process creation event is detected, the event handler retrieves the process name and ID from the event properties and performs some action. In this case, a message box is displayed with the process information.
The script block containing the CustomApplicationContext
class is executed using powershell.exe
with the necessary parameters to bypass execution policies and create a new PowerShell host.
Modify the event handler and the action inside it according to your requirements. You can also adjust the WMI query in the query
variable if you need to filter the process creation events based on specific criteria.
Run the PowerShell script to start listening for process creation events, and the CustomApplicationContext
will be instantiated and run in the background while handling the events.
Note: Ensure that you have appropriate permissions to access and subscribe to WMI events on the system.