0

I have written a simple powershell script to trigger an email notification and restart a service when a service failure occurs, and have been testing it on my desktop by crashing the Windows Audio server ("Audiosrv").

The script is set up to run by going into Services -> right click on service -> Properties -> Recovery -> First/Second/Subsequent Failures -> Run A Program, with the program parameters listed below.

The Local Service account (NT AUTHORITY\LOCAL SERVICE) runs this script on the service failure, this is known by the whoami command output during the script. This account can use the Send-MailMessage cmdlet (I receive the email), but it cannot use the Restart-Service cmdlet (or Start-Service, or net start, or sc start?). See the error message, this is the same error message received when trying to run Restart-Service as a user without admin privilege.

How can I temporarily elevate privileges so that this script can restart the service? Or what should I do differently?


Run Program:

C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe

Command Line Parameters:

-File C:\Scripts\StoppedServiceNotifyEmail.ps1



Powershell script (emails/hostnames redacted):

$serviceName = "Audiosrv"
$serviceDisplayName = "Windows Audio"
$fromAddress = "xxxx@xxxxxxxxx.org"
$toAddress = "xxxx@xxxxxxxxx.org"

$initialFailedBody=@"
<head>
   <style type='text/css'>
       body {
           font-family: Calibri;
           font-size: 11pt;
           color: black;
       }
   </style>
</head>
<body>
    <p>$serviceDisplayName ($serviceName) on $env:computername has failed, attempting to restart the service.</p>
</body>
"@

whoami | Out-File -FilePath C:\Scripts\whoami_after_Audiosrv_fail.txt
Send-MailMessage -smtpServer xxxxxxxxxxxxx -Port xxx -from $fromAddress -to $toAddress -subject "$serviceDisplayName ($serviceName) failed on $env:computername" -body $initialFailedBody -BodyAsHTML -priority High
Start-Sleep -s 10
Restart-Service -Name $serviceName


Powershell error output:

Restart-Service : Service 'Windows Audio (Audiosrv)' cannot be stopped due to the following
error: Cannot open Audiosrv service on computer '.'.
At C:\Util\StoppedServiceNotifyEmail.ps1:82 char:5
+     Restart-Service -Name $serviceName
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (System.ServiceProcess.ServiceController:ServiceControl
   ler) [Restart-Service], ServiceCommandException
    + FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Commands.RestartServiceCom
   mand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.