{"id":422,"date":"2021-08-10T13:12:50","date_gmt":"2021-08-10T20:12:50","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/powershell-community\/?p=422"},"modified":"2021-08-10T13:14:36","modified_gmt":"2021-08-10T20:14:36","slug":"how-can-i-be-notified-any-time-a-service-goes-down","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/powershell-community\/how-can-i-be-notified-any-time-a-service-goes-down\/","title":{"rendered":"How can\u00a0I\u00a0be\u00a0notified\u00a0any\u00a0time\u00a0a\u00a0service\u00a0goes\u00a0down?"},"content":{"rendered":"<p>Q:\u00a0How\u00a0can\u00a0I\u00a0be\u00a0notified\u00a0any\u00a0time\u00a0a\u00a0service\u00a0goes\u00a0down?<\/p>\n<p>A:\u00a0The short quick answer to utilizing\u00a0WMI\u00a0and\u00a0PowerShell\u00a07.<\/p>\n<p>You use PowerShell to create temporary event monitoring using WMI. Then WMI monitors any service changes and generates an alert once it detects a change.<\/p>\n<h2>Basic Requirement<\/h2>\n<p>To achieve this, you need Windows PowerShell 5.1 and above.<\/p>\n<p>This post uses the latest version of PowerShell 7. So if you are don&#8217;t yet have PowerShell 7, see the Microsoft documentation on how to <a href=\"https:\/\/docs.microsoft.com\/powershell\/scripting\/install\/installing-powershell-core-on-windows\">Install PowerShell 7 on Windows<\/a>.<\/p>\n<p>Also, make sure that PowerShell is running as administrator.<\/p>\n<h2>Finding the Required Class<\/h2>\n<p>Before going into details, you need to find the required class to monitor. To get a list of all available classes, use the following code.<\/p>\n<pre><code class=\"language-powershell-console\">PS&gt; Get-CimClass -Namespace root\\cimv2\n\n   NameSpace: ROOT\/CIMV2\n\nCimClassName                        CimClassMethods      CimClassProperties\n------------                        ---------------      ------------------\n__SystemClass                       {}                   {}\n__thisNAMESPACE                     {}                   {SECURITY_DESCRIPTOR}\n__Provider                          {}                   {Name}\n__Win32Provider                     {}                   {Name, ClientLoadableCLSID, CLSID, Concurrency\u2026}\n__ProviderRegistration              {}                   {provider}\n__EventProviderRegistration         {}                   {provider, EventQueryList}\n__ObjectProviderRegistration        {}                   {provider, InteractionType, QuerySupportLevels, SupportsBatch\u2026\n__ClassProviderRegistration         {}                   {provider, InteractionType, QuerySupportLevels, SupportsBatch\u2026\n__InstanceProviderRegistration      {}                   {provider, InteractionType, QuerySupportLevels, SupportsBatch\u2026\n__MethodProviderRegistration        {}                   {provider}\n__PropertyProviderRegistration      {}                   {provider, SupportsGet, SupportsPut}\n__EventConsumerProviderRegistration {}                   {provider, ConsumerClassNames}<\/code><\/pre>\n<p>The returned result represents all the available classes in the namespace. For this tutorial, the focus is on Windows services, which is represented by <strong>Win32_Service<\/strong>.<\/p>\n<p>To Enumerate the <strong>Win32_Services<\/strong> WMI class and get all the available services using PowerShell run the following code.<\/p>\n<pre><code class=\"language-powershell-console\">PS&gt; Get-CimInstance -Namespace root\\CIMV2 -ClassName win32_service\n\nProcessId Name                                     StartMode State   Status  ExitCode\n--------- ----                                     --------- -----   ------  --------\n3784      AdobeARMservice                          Auto      Running OK      0\n3792      AdobeUpdateService                       Auto      Running OK      0\n3800      AGMService                               Auto      Running OK      0\n3824      AGSService                               Auto      Running OK      0\n0         AJRouter                                 Manual    Stopped OK      1077\n0         ALG                                      Manual    Stopped OK      1077\n0         AppIDSvc                                 Manual    Stopped OK      1077\n6708      Appinfo                                  Manual    Running OK      0\n21444     AppMgmt                                  Manual    Running OK      0\n0         AppReadiness                             Manual    Stopped OK      1077\n0         AppVClient                               Disabled  Stopped OK      1077\n0         AppXSvc                                  Manual    Stopped OK      0\n0         AssignedAccessManagerSvc                 Manual    Stopped OK      1077<\/code><\/pre>\n<p>For now, you can use PowerShell to find the required class, and enumerate it to get the available services. Let&#8217;s go deeper now and start creating the WMI Event Subscription.<\/p>\n<p>There are three steps you need to follow to create a temporary WMI Event Subscription:<\/p>\n<ul>\n<li>Create a WMI query language query.<\/li>\n<li>Register this query.<\/li>\n<li>Obtain any events generated.<\/li>\n<\/ul>\n<h2>Creating WMI Query<\/h2>\n<p>WMI has many special classes that you can use to detect changes to other WMI classes. For example, you can use the <strong>CIM_InstModification<\/strong> class to monitor the targeted class, in this case <strong>Win32_Service<\/strong><\/p>\n<p>You have to create a WMI query using <a href=\"https:\/\/docs.microsoft.com\/windows\/win32\/wmisdk\/wql-sql-for-wmi\">WMI Query Language<\/a>.<\/p>\n<p>The WQL syntex structure looks like this:<\/p>\n<pre><code>Select * from &lt;WMI System Class&gt; within &lt;Number of Seconds&gt; where TargetInstance ISA &lt;WMI Class name&gt;\n<\/code><\/pre>\n<p>Let apply the same to <strong>Win32_Serivce<\/strong>. Start by creating a PowerShell variable, in our case, you construct the query as follows:<\/p>\n<pre><code class=\"language-powershell-console\">$query = \"Select * from CIM_InstModification within 10 where TargetInstance ISA 'Win32_Service'\"<\/code><\/pre>\n<p>A full explanation for the WQL query is available in <a href=\"https:\/\/adamtheautomator.com\/your-goto-guide-for-working-with-windows-wmi-events-and-powershell\/\">Your Goto Guide for Working with Windows WMI Events and PowerShell<\/a>.<\/p>\n<h2>Registering The Query<\/h2>\n<p>We have the WQL query, let&#8217;s move to the next and register the query to the WMI events by using the <a href=\"https:\/\/docs.microsoft.com\/powershell\/module\/cimcmdlets\/register-cimindicationevent\">Register-CimIndicationEvent<\/a>. The <code>Register-CimIndicationEvent<\/code> is used to subscribe to events generated from the system. And in our case, it subscribes to events generated from the <code>$query<\/code>.<\/p>\n<pre><code class=\"language-powershell-console\">Register-CimIndicationEvent -Namespace 'ROOT\\CIMv2' -Query $query -SourceIdentifier 'WindowsServices' -MessageData 'Service Status Change'<\/code><\/pre>\n<p>To confirm the successful registration, type the following cmdlet <code>Get-EventSubscriber<\/code>, the output looks like the following<\/p>\n<pre><code class=\"language-powershell-console\">PS&gt; Get-EventSubscriber\n\nSubscriptionId   : 1\nSourceObject     : Microsoft.Management.Infrastructure.CimCmdlets.CimIndicationWatcher\nEventName        : CimIndicationArrived\nSourceIdentifier : **WindowsServices**\nAction           :\nHandlerDelegate  :\nSupportEvent     : False\nForwardEvent     : False<\/code><\/pre>\n<p>And that&#8217;s all that we need, simple as that.<\/p>\n<h2>Reading the events<\/h2>\n<p>Now the event is registered and active. Next, create an event, and by that, I mean stopping or starting a service.<\/p>\n<p>Try <strong>Windows Update<\/strong> service (wuauserv), run the following cmdlet to see the status of the wuauserv service.<\/p>\n<pre><code class=\"language-powershell-console\">PS&gt; Get-Service wuauserv\n\nStatus   Name               DisplayName\n------   ----               -----------\nRunning  wuauserv           Windows Update<\/code><\/pre>\n<p>So the service is running, let stop it by typing the following<\/p>\n<pre><code class=\"language-powershell\">PS&gt; Stop-Service wuauserv<\/code><\/pre>\n<p>To see the newly created events, type <code>Get-Event<\/code> Look at the <strong>MessageData<\/strong>, it&#8217;s the same message used in the <code>Register-CimIndicationEvent<\/code>.<\/p>\n<pre><code class=\"language-powershell-console\">PS&gt; $EventVariable=Get-Event\nPS&gt; $EventVariable\n\nComputerName     :\nRunspaceId       : 91c6b6fb-cda9-4b15-983f-d7af1f639358\nEventIdentifier  : 1\nSender           : Microsoft.Management.Infrastructure.CimCmdlets.CimIndicationWatcher\nSourceEventArgs  : Microsoft.Management.Infrastructure.CimCmdlets.CimIndicationEventExceptionEventArgs\nSourceArgs       : {Microsoft.Management.Infrastructure.CimCmdlets.CimIndicationWatcher,\n                   Microsoft.Management.Infrastructure.CimCmdlets.CimIndicationEventExceptionEventArgs}\nSourceIdentifier : WindowsServices\nTimeGenerated    : 30-Jul-21 12:08:06 AM\nMessageData      : Service Status Change<\/code><\/pre>\n<p>To find the current state of this event<\/p>\n<pre><code class=\"language-powershell-console\">PS&gt; $EventVariable.SourceEventArgs.NewEvent.PreviousInstance\n\nProcessId Name     StartMode State   Status ExitCode\n--------- ----     --------- -----   ------ --------\n16508     wuauserv Manual    Running OK     0<\/code><\/pre>\n<p>This WMI monitoring remains active as long as the PowerShell console. It creates such a temporary job which runs in the background to monitor the services class. You can also end this process by rebooting the computer. Hope you learned something new today.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Q:\u00a0How\u00a0can\u00a0I\u00a0be\u00a0notified\u00a0any\u00a0time\u00a0a\u00a0service\u00a0goes\u00a0down? A:\u00a0The short quick answer to utilizing\u00a0WMI\u00a0and\u00a0PowerShell\u00a07. You use PowerShell to create temporary event monitoring using WMI. Then WMI monitors any service changes and generates an alert once it detects a change. Basic Requirement To achieve this, you need Windows PowerShell 5.1 and above. This post uses the latest version of PowerShell 7. So if [&hellip;]<\/p>\n","protected":false},"author":53227,"featured_media":77,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[13],"tags":[42,3,34],"class_list":["post-422","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-powershell","tag-events","tag-powershell","tag-wmi"],"acf":[],"blog_post_summary":"<p>Q:\u00a0How\u00a0can\u00a0I\u00a0be\u00a0notified\u00a0any\u00a0time\u00a0a\u00a0service\u00a0goes\u00a0down? A:\u00a0The short quick answer to utilizing\u00a0WMI\u00a0and\u00a0PowerShell\u00a07. You use PowerShell to create temporary event monitoring using WMI. Then WMI monitors any service changes and generates an alert once it detects a change. Basic Requirement To achieve this, you need Windows PowerShell 5.1 and above. This post uses the latest version of PowerShell 7. So if [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/posts\/422","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/users\/53227"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/comments?post=422"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/posts\/422\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/media\/77"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/media?parent=422"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/categories?post=422"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/tags?post=422"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}