An (almost!) Dynamic DNS Script in Powershell

So in the last few months I have been learning a lot (a lot!) and I want to share my knowledge. One thing I whipped up on my way home from work was a small script to email me if my local IP address changed.

Personally, I own a .com which I have a subdomain A record to my home IP address, and I use this to keep that A record relevant. You could also manually enter your IP address and have it notify you if it changes, if you didn’t want to use a domain.

$users = "you@email.com" 
$fromemail = "thiscanbe@anything.com" # Email which the alert will come from
$server = "mail.yourserver.com" # SMTP server - you may need to include username/password, but my ISP (Optus) provides a free open one for subscribers

#Domain to check for discrepancies
$domain = "myipdomain.com"

#Your current IP address provided by IPify API
$ip = Invoke-RestMethod -Uri 'https://api.ipify.org?format=json' 
$ip = $ip.ip

#The IP address of your domain. You could skip this and just assign your current IP as a sting to check for differences
$dns = [System.Net.Dns]::GetHostAddresses($domain)[0].IPAddressToString

#What the email will contain. Feel free to modify this.
$HTMLmessage = @"

<h1>Alert Alert</h1>

Your Public IP address may have changed!
The IP address detected by this script is: <b>$ip</b>
<em>BUT</em> the IP address detected on your domain is: <b>$dns</b>

Please rectify the issue. This is an automated email and will continue to run until stopped manually or domain updated.

Warm Regards,
The robot in your server "@

#The check if your IP doesn't match the domain IP, and it's not blank
if ($ip -ne $dns -and $ip -ne "") {
#Send the email
send-mailmessage -from $fromemail -to $users -subject "Public IP Address Change!" -BodyAsHTML -body $HTMLmessage -priority Normal -smtpServer $server 
}

And it’s as simple as that. I have the script run every 10 minutes or so using Windows Task Scheduler. If you IP does change, be aware it will keep sending the emails every 10 minutes till you either fix the domain, or disable the script.

While I was researching this I did come across the face that Hover (my personal domain registrar) has an unofficial API that you would be able to use to automatically update your A record. This would mean the script could be completely automated, and work as well as the DynDNS settings in your router.

I hope you find this helpful! If you have any questions, ask in the comments 🙂

-Andrew