Monitor process startup/shutdown using WMI & PowerShell

Recently I was working on a project, where I needed to monitor process for startup/shutdown events,  after searching internet  found that it can be easily done using WMI and PowerShell .

WMI (Windows Management Instrumentation) is a technology built in to Windows since Windows 2000, that provides standard interface to manage windows systems. For example it can used to find software products installed in single or multiple machines in network or to verify necessary OS service pack is installed on all machines in the network.

PowerShell provides easy way of accessing WMI functionality using simple scripting language.

Here is how you can monitor for process startup using PowerShell & WMI events

1. Launch PowerShell and enter following command. This command will register for process started event and prints statement in console whenever notepad.exe is executed.

Register-WMIEvent -query “SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName=’notepad.exe'” -SourceIdentifier “testevent” -action { $e = $Event.SourceEventArgs.NewEvent

Write-Host $e.ProcessName,” started ” }

2. Now launch notepad and observer that console has message confirming the same.

3. Once you are done, unregister the event by entering following command

Unregister-Event testevent

4. You can also see list of event subscribers with “Get-EventSubscriber” command.

Some more examples of using WMI & PowerShell

1.Monitor process stop events

Register-WMIEvent -query “SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName=’notepad.exe'” -SourceIdentifier “testevent” -action { $e = $Event.SourceEventArgs.NewEvent

Write-Host $e.ProcessName,” stopped ” }

2. Monitor Windows Service stop/start status. Replace “TargetInstance.Name” value with your service name

Register-WMIEvent -query “Select * From __InstanceOperationEvent within 1 Where TargetInstance ISA ‘Win32_Service’ and TargetInstance.Name=’Fax'” -sourceIdentifier “MyServMonitor” -action { Write-host “Service Name :”,$EventArgs.NewEvent.TargetInstance.Name ,” Service State :”, $EventArgs.NewEvent.TargetInstance.State }

image

You can also do the same event monitoring using WMI & C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace WmiEventTest
{
    class ServiceStatusMonitor
    {
        static void Main(string[] args)
        {

            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ServiceStatusMonitor  ");
                Environment.Exit(0);
            }
            string WMI_EVENT_QUERY = @"SELECT * FROM __InstanceModificationEvent
                WITHIN 1 WHERE TargetInstance ISA 'Win32_Service'";

            string WMI_EVENT_QUERY_WITH_SERVICE_NAME = WMI_EVENT_QUERY
                    + " and TargetInstance.Name = '{0}'";
            WqlEventQuery serviceModificationEvent =
                    new WqlEventQuery(string.Format(WMI_EVENT_QUERY_WITH_SERVICE_NAME, args[0]));
            ManagementEventWatcher eventWatcher =
                    new ManagementEventWatcher(serviceModificationEvent);
            eventWatcher.EventArrived +=
                    new EventArrivedEventHandler(Watcher_EventArrived);
            Console.WriteLine("Waiting for service status change events ...");
            eventWatcher.Start();
            Console.ReadLine();
        }

        static void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            string eventType = e.NewEvent.ClassPath.ClassName;

            switch (eventType)
            {
                case "__InstanceCreationEvent":

                    Console.BackgroundColor = ConsoleColor.Blue;
                    Console.WriteLine("'{0}' Service created ....",
                            Environment.GetCommandLineArgs()[1]);
                    Console.ResetColor();
                    break;
                case "__InstanceDeletionEvent":

                    Console.BackgroundColor = ConsoleColor.Green;
                    Console.WriteLine("'{0}' Service deleted ....",
                        Environment.GetCommandLineArgs()[1]);
                    Console.ResetColor();
                    break;

                case "__InstanceModificationEvent":

                    Console.BackgroundColor = ConsoleColor.Blue;
                    ManagementBaseObject obj = (ManagementBaseObject)e.NewEvent["TargetInstance"];
                    Console.WriteLine("'{0}' Service Modified ( {1} )",
                        Environment.GetCommandLineArgs()[1], obj["State"]);
                    Console.ResetColor();
                    break;
            }

        }
    }
}

Resources

1. Introduction to WMI

2. Receiving WMI Events

3. PowerShell for event monitoring.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s