Skip to content

Instantly share code, notes, and snippets.

@timelf123
Created December 12, 2022 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelf123/644bdf91e7153bec9028cc61c41a604d to your computer and use it in GitHub Desktop.
Save timelf123/644bdf91e7153bec9028cc61c41a604d to your computer and use it in GitHub Desktop.
Cross platform powershell to notify you when your dynamic IP changes
<#
Before you execute this, run this in powershell to get notification script installed:
Install-Module -Name PoshNotify
#>
$LOG="$HOME/.myip"
# Update the log file and show a notification with the current IP
function Update() {
$ip_cur | Set-Content -NoNewline $LOG
$hostname = hostname
# Needs `Install-Module -Name PoshNotify`
Send-OSNotification -Title "$($hostname) IP changed" -Body "Current IP: $ip_cur Date: $(Get-Date -Format t)"
}
function InitLog() {
$ip_cur | Set-Content -NoNewline $LOG
}
while ($true) {
# Check if the user has pressed Ctrl+C
if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
if ($key.VirtualKeyCode -eq 67 -and $key.Modifiers -eq "Control") {
break
}
}
$ip_response= Invoke-RestMethod -uri https://ipinfo.io/json | select-object -ExpandProperty ip
$ip_cur= $ip_response.ToString()
# If IP current is null exit, i.e. Invoke-WebRequest fails
if (-not $ip_cur) {
exit 1
# If the log file doesn't exist
} elseif (-not (Test-Path $LOG)) {
InitLog
} else {
# Check if the IP has changed
$ip_prev = Get-Content $LOG -First 1
if ("$ip_prev" -ne "$ip_cur") {
Update
}
}
# Wait for one minute before checking again
Start-Sleep -Seconds 60
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment