Skip to content

Instantly share code, notes, and snippets.

@dmauser
Created February 3, 2026 22:21
Show Gist options
  • Select an option

  • Save dmauser/a62d88a699fe1c42f13fd31b8477ddd6 to your computer and use it in GitHub Desktop.

Select an option

Save dmauser/a62d88a699fe1c42f13fd31b8477ddd6 to your computer and use it in GitHub Desktop.
traffic manager failover
$tmuri="https://webdemo.danmauser.com" #Replace with your website associate to Traffic Manager
# WebTest with DNS resolution (using nslookup)
While ($true) {
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Resolve final single IP (follow one CNAME hop if present, then first A record) via nslookup
$ipText = $null
try {
$baseHost = ([System.Uri]$tmuri).Host
# CNAME hop (one level)
$finalHost = $baseHost
$cnameOut = (& nslookup -type=CNAME $baseHost 2>&1) -join "`n"
$cnCandidates = @()
$cnCandidates += ([regex]::Matches($cnameOut, 'canonical name\s*=\s*([a-z0-9\.\-]+)', 'IgnoreCase') | ForEach-Object { $_.Groups[1].Value })
$cnCandidates += ([regex]::Matches($cnameOut, '\bname\s*=\s*([a-z0-9\.\-]+)', 'IgnoreCase') | ForEach-Object { $_.Groups[1].Value })
if ($cnCandidates -and $cnCandidates[0]) {
$finalHost = $cnCandidates[0].TrimEnd('.')
}
# A records - pick the first resolved IP (skip DNS server IP)
$aOut = (& nslookup -type=A $finalHost 2>&1) -join "`n"
$lines = $aOut -split "`r?`n"
$collect = $false
$finalIp = $null
foreach ($line in $lines) {
if (-not $collect) {
if ($line -match '^\s*Name\s*:' -or $line -match "^\s*$([Regex]::Escape($finalHost))\b") {
$collect = $true
}
continue
}
if ($line -match '\b(?:\d{1,3}\.){3}\d{1,3}\b') {
$m = [regex]::Match($line, '\b(?:\d{1,3}\.){3}\d{1,3}\b')
if ($m.Success) { $finalIp = $m.Value; break }
}
}
if (-not $finalIp) {
# Fallback: skip the first IPv4 (DNS server) if present, then take the next one
$allIps = ([regex]::Matches($aOut, '\b(?:\d{1,3}\.){3}\d{1,3}\b') | ForEach-Object { $_.Value })
if ($allIps.Count -gt 1) {
$finalIp = $allIps[1]
} else {
$finalIp = $allIps | Select-Object -First 1
}
}
$ipText = if ($finalIp) { $finalIp } else { 'NONE' }
} catch {
$ipText = 'ERR:' + ($_.Exception.Message -replace '\r?\n',' ' -replace '\s+',' ').Trim()
}
try {
$resp = Invoke-WebRequest -Uri $tmuri -DisableKeepAlive -ErrorAction Stop
$content = ($resp.Content | Out-String)
$content = ($content -replace '\r?\n',' ' -replace '\s+',' ').Trim()
Write-Host "[$ts] IP=$ipText $($resp.StatusCode) $($resp.StatusDescription) $content"
} catch {
$err = ($_.Exception.Message -replace '\r?\n',' ' -replace '\s+',' ').Trim()
Write-Host "[$ts] IP=$ipText ERROR $err"
}
Start-Sleep -Seconds 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment