简体   繁体   中英

Running a Powershell Script on Windows Service Failure. Works when run manually but not when service fails. Advice needed

So I have been working on a script to essentially send an email when a Service fails. The script works just fine, as I've run it manually from PowerShell. I get the email and everything checks out. I then add this to the service: Service Recovery Options

I tell it to run Powershell by linking to the executable:

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

And the execute the following script:

-command C:\Users\andreand\Desktop\Sendmail.ps1

As mentioned, I tried this manually in PowerShell, and I got an error. If I append the PowerShell location before the -command it works. Like so:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command C:\Users\andreand\Desktop\Sendmail.ps1

So this works if I run it manually, but when the service fails, nothing happens. I trigger a failure by doing /taskkill /F /PID pid , and I can see the service has stopped.

What am I missing? I feel like I am so close and it is frustrating!

As Mark Wragg here suggested, the problem lies in that I encrypted the string with one user account, but trying to decrypt it with another. By not using encryption for the password, it works.

I am still trying to figure out if there is any way to keep the encryption and have this work.

Furthermore, I am now trying to embed the failed service in the email subject field, but I am unsure how to do this. I have seen the Get-Service Cmdlet, but that seems to fetch an entire list, where I would just need it to read back the service that failed. Any help on this is most welcome.

EDIT: I have now found solutions to both encrypting the password and retrieving a list of services. To encrypt the password, I used an encryption key. It goes something like this:

# Change this location as necessary.
PS C:\Users\andreand> $File = 'C:\SomeLocation\Key.txt'

PS C:\Users\andreand> [Byte[]] $Key = (1..16)

# The password for the mail account / SMTP client.
PS C:\Users\andreand> $Password = 'Passwordgoeshere' | ConvertTo-SecureString -AsPlainText -Force

PS C:\Users\andreand> $Password | ConvertFrom-SecureString -Key $Key | Out-File 
$File 

After this, I input the following into my script to retrieve the encrypted key:

$File = 'C:\SomeLocation\Key.txt'
[Byte[]] $Key = (1..16)
$Password = Get-Content $File | ConvertTo-SecureString -Key $Key

For retrieving the list of services, I used the Get-Service cmdlet, but with some filtering to find the services I wanted. Like so:

$Services = Get-Service | Where-Object {$_.DisplayName -like "ServiceName*"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM