One of the first powershell scripts I wanted to share is a script that checks your WAN ip and notifies you by e-mail when it changes.

Background:

I’ve used to sign up with a dynamic DNS provider but my router stopped updating my ip address to that DynDNS provider. After a while I received an e-mail that my host was being deleted from the database if I did not take action. A few e-mail later I decided to say goodbye to that DynDNS provider because my IP-Address does not change that much at all (I still have the same address as a year ago). So I wrote a script that checks the IP address of your FQDN and uses the automation page of  WhatisMyIP.com  to read you current WAN ip address and sends you an e-mail when it has changed.

Code Break down:

This is where you put your router’s FQDN

$TargetDomain = "Your Host FQDN" #Enter your FQDN that is linked to your WAN ip address

This function takes care of sending the e-mail

Function SendMail {
$EmailFrom = "from@yourdomain.com" #Enter the e-mail address it should send the message from.
$EmailTo = "to@yourdomain.com" #Enter the e-mail address it should send the message to.
$Subject = "External IP Address Has Changed ($Current_WAN_IP)" #Enter your subject the e-mail message should contain.
$Body = "Please Update your DNS records to $Current_WAN_IP" #Enter the message that the e-mail should contain.
$SMTPServer = "SMTP SERVER FQDN" #Enter the FQDN of your SMTP server eg. smtp.gmail.com
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) #Enter your SMTP Port eg. 587
$SMTPClient.EnableSsl = $true # Change to $false if you don't want to use SSL
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("your smtp username", "your smtpserver password") #Comment line with '#' if you don't need authentication
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}

Here is where the magic happens, this code checks your WAN IP and executes the correct action

# Do not change anything below this line.
$DNS_WAN_IP = [System.Net.Dns]::GetHostAddresses("$TargetDomain") | select-object IPAddressToString -expandproperty IPAddressToString
Write-host "Resolved IP Address of $TargetDomain = $DNS_WAN_IP"
$Current_WAN_IP = (New-Object System.Net.WebClient).DownloadString("http://automation.whatismyip.com/n09230945.asp")
Write-host "Current WAN IP Address = $Current_WAN_IP"
if ($Current_WAN_IP -ne $DNS_WAN_IP) {
 if ((@([Byte[]][char[]]$Current_WAN_IP -eq 46).Count)-ne 3) {write-host "No Valid IP Address Retrieved";Exit}
 Write-Host "IP Address Has Changed, Sending e-mail"
 SendMail
 exit
 }
 Else {write-host "No IP Address Change Detected";Exit}

This script is tested with Powershell V2 but should work in V1 as well. I’ll Hope you like the script full version can be downloaded here: CheckWANIP (1338)