Intro
I had a few PowerShell tasks set up in my server with no way of knowing their status unless I checked for logs. Logging in and searching for logs easily becomes a hassle when you have more than one VM. I needed a less time consuming method, so I found a way to send push alerts to my mobile phone using ntfy.
Pre-requisites
For this setup to work, you should have a running instance of ntfy.sh. You can find the installation instructions here. You can find my personal docker compose file here
I am running the stock PowerShell version installed in Windows Server 2016 and encountered some issues reaching my ntfy endpoint due to certificate validation failures. To avoid this, I added the following in my script.
Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$allProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $allProtocols
Powershell Script
To send a message to ntfy, you just have to add a POST request to your script as follows:
$bearerToken="your encoded token"
$Request = @{
Method = "POST"
URI = "https://ntfy.yourdomain.com/scripts?auth=$bearerToken"
Headers = @{
Title = $title # title is the notification header
}
Body = $body # body is the content of your notification
}
Invoke-RestMethod @Request
To get an access token, log into your ntfy web interface and navigate to your account settings. Create an access token and make sure to select Token never expires
for convenience. Once created, copy the token and format it as Bearer tk_token
. Finally, encode this entire string in base64 using an online tool like this one.
Done!
If everything is set up correctly, you will be able to receive status information from your scripts directly to your phone.