<#
.SYNOPSIS
Manages WireGuard tunnel service based on public IP changes.
Version 1.8: Added aggressive service cleanup (stop + force terminate) on tunnel failure.
Previous changes:
- Version 1.5: Added connectivity check to Test-TunnelUp; stops service if check fails. DAILY LOG ROTATION.
- Version 1.6: Fixed logic to preserve healthy tunnels when switching to Expected IP.
- Version 1.7: Added single retry logic for broken tunnels on Expected IP.
.DESCRIPTION
- Retrieves the current public IP.
- If IP matches ISP IP and tunnel isn't established, stops WireGuard service.
- If IP doesn't match ISP IP:
- If service runs but tunnel isn't up OR connectivity fails, stops service.
- If service is stopped, attempts to start it with retries.
- Failed attempts trigger a backoff period.
- LOGS ARE ROTATED DAILY (configurable): Log file overwritten after N hours.
- Logs are stored in the CURRENT USER'S "Documents\WireGuardLogs" folder (dynamic path).
- On tunnel failure, performs AGGRESSIVE CLEANUP (service stop + process termination if needed).
REQUIREMENTS:
- WireGuard installed as a Windows Service.
- Scheduled Task to run this script periodically (every 5-10 minutes recommended).
#>
=======================================================================================
--- ADJUSTABLE CONFIGURATION PARAMETERS (CHANGE THESE AS NEEDED) ---------------------
=======================================================================================
***** 1. NETWORK SETTINGS *****
ExpectedPublicIP = "1.2.3.4" # <<< CHANGE: Your HOME/ISP public IP address (e.g., 203.0.113.42)
IPCheckURI = "https://icanhazip.com" # <<< CHANGE IF NEEDED: Service to fetch your current public IP (must return plain text IP)
$TunnelTestIP = "10.0.0.1" # <<< CHANGE: IP address ONLY reachable via WireGuard tunnel (server's WG IP)
***** 2. WIREGUARD SETTINGS *****
WireGuardTunnelName="wg−env:COMPUTERNAME" # <<< USUALLY FINE: Matches your WireGuard .conf file (without .conf extension)
# Example: if your file is wg-myhome.conf, set this to wg-myhome
***** 3. TIMEOUTS & RETRIES *****
TimeoutSeconds = 10 # <<< CHANGE IF SLOW NETWORK: Timeout for fetching public IP (seconds)
GetIPMaxRetries = 3 # <<< CHANGE IF UNSTABLE NETWORK: How many times to retry fetching public IP
GetIPRetryDelay = 5 # <<< CHANGE IF NEEDED: Delay between IP fetch retries (seconds)
TunnelStartRetries = 3 # <<< CHANGE IF WG IS FLAKY: How many times to retry starting WireGuard service
TunnelStartDelay = 15 # <<< ADJUST BASED ON WG INIT TIME: Seconds to wait for tunnel to come up after start
PingTimeoutSeconds = 5 # <<< FINE-TUNE FOR LATENCY: Timeout for pinging $TunnelTestIP (seconds)
***** 4. BACKOFF & LOGGING *****
TunnelBackoffHours = 1 # <<< CHANGE FOR AGGRESSIVE NETWORKS: Hours to "cool down" after repeated failures
LogRotationAgeHours = 24 # <<< ADJUST FOR LOG SIZE: Rotate (overwrite) log file after this many hours
# Set to 168 (7 days) if you prefer weekly rotation
***** 5. SERVICE CONTROL *****
ServiceStopWaitSeconds = 10 # <<< RARELY NEEDS CHANGE: Timeout waiting for WireGuard service to stop cleanly
ForceTerminateOnFailure = true # <<< SET TO false IF YOU PREFER GENTLE STOPS ONLY (no process killing)
# If $true, script will FORCE-KILL WireGuard process if service stop fails
=======================================================================================
--- INTERNAL CONSTANTS (DON'T TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING) ---------------
=======================================================================================
$ServiceName = "WireGuardTunnel`$$WireGuardTunnelName" # Derived service name (matches WG installation)
=======================================================================================
--- DYNAMIC LOG PATHS (AUTO-DETECTED, NO NEED TO CHANGE) ----------------------------
=======================================================================================
These resolve to the CURRENT USER'S "Documents\WireGuardLogs" folder, even if redirected
DocumentsPath=[EnvironmenLogDir = Join-Path -Path LogFile = Join-Path -Path BackoffFile = Join-Path -Path $LogDir -ChildPath "wg_backoff.tmp"
Ensure log directory exists (done ONCE at startup)
if (-not (Test-Path LogDir)) {
New-Item -ItemType Directory -Path LogDir -Force | Out-Null
Write-Host "Created log directory: $LogDir" -ForegroundColor Cyan
}
--- Exit Codes (for task schedulers, monitoring tools) ---
EXITSUCCESS=0EXIT_CONFIG_ERROR = 1
EXIT_SERVICE_ERROR = 3
#region --- Helper Functions ---
Function Write-Log {
Param(
[string]Message,[ValidateSet("INFLevel = "INFO"
)
logLine = "Level - $Message"
# Daily log rotation check
if (Test-Path $LogFile) {
$logAge = (Get-Date) - (Get-Item $LogFile).LastWriteTime
if ($logAge.TotalHours -ge $LogRotationAgeHours) {
Write-Host "Log file older than $LogRotationAgeHours hours. Rotating (overwriting)..." -ForegroundColor Yellow
try {
[System.IO.File]::WriteAllText($LogFile, "") # Clear file
}
catch {
Write-Host "Failed to rotate log file: $($_.Exception.Message)" -ForegroundColor Red
}
}
}
switch ($Level) {
"INFO" { Write-Host $logLine -ForegroundColor Cyan }
"WARN" { Write-Host $logLine -ForegroundColor Yellow }
"ERROR" { Write-Host $logLine -ForegroundColor Red }
}
try {
[System.IO.File]::AppendAllText($LogFile, "$logLine`r`n")
}
catch {
Write-Host "Log write failed: $($_.Exception.Message)" -ForegroundColor Red
}
}
Function Get-PublicIP {
attempt=0while(attempt -lt GetIPMaxRetries) {
try {
ip = (Invoke-RestMethod -Uri IPCheckURTimeoutSeconds).Trim()
if (') { return IPCheckURI" -Level WARN
}
catch {
Write-Log "IP fetch failed (attempt attempt + 1)): _.Exception.Message)" -Level WARN
}
GetIPRetryDelay
}
Write-Log "Public IP fetch failed after null
}
Function Get-WGService {
return Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
}
Function Start-WGService {
try {
Write-Log "Starting WireGuard service..."
Start-Service -Name ServiceName−ErrorActionStopWrTunnelStartDelay seconds for tunnel to potentially come up..."
Start-Sleep -Seconds (false
}
}
Function Stop-WGService {
svc=Get−WGServiceif(−notsvc) {
Write-Log "WireGuard service not found for stopping." -Level WARN
return true
}
if (svc.Status -ne 'Running') {
Write-Log "WireGuard service is already not running (svc.Status))."
return $true
}
try {
Write-Log "Stopping WireGuard service..."
Stop-Service -Name $svc.Name -Force -ErrorAction Stop
$svc.WaitForStatus('Stopped', (New-TimeSpan -Seconds $ServiceStopWaitSeconds))
Write-Log "Service stopped."
return $true
}
catch {
Write-Log "Service stop failed: $($_.Exception.Message)" -Level ERROR
return $false
}
}
Function Test-TunnelUp {
iface = Get-NetAdapter | Where-Object { _.InterfaceDescription -like "WireGuard Tunnel*" -and .Name−like"WireGuardTunnelName*"}
if (-not iface) {
Write-Log "Tunnel interface 'WireGuardTunnelName' not found." -Level WARN
return $false
}
if ($iface.Status -ne "Up") {
Write-Log "Tunnel interface '$($iface.Name)' found but is DOWN." -Level WARN
return $false
}
Write-Log "Tunnel interface '$($iface.Name)' is UP. Testing connectivity..."
if (-not $TunnelTestIP) {
Write-Log "No TunnelTestIP configured. Assuming tunnel is up if interface is up." -Level WARN
return $true
}
Write-Log "Pinging $TunnelTestIP via tunnel..."
$timeoutMs = $PingTimeoutSeconds * 1000
ping.exe -n 1 -w $timeoutMs $TunnelTestIP | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Log "Tunnel connectivity VERIFIED to $TunnelTestIP."
return $true
}
else {
Write-Log "Tunnel connectivity FAILED. Could not ping $TunnelTestIP (timeout: $($PingTimeoutSeconds)s). ping.exe Exit Code: $LASTEXITCODE" -Level WARN
return $false
}
}
Function Set-Backoff {
try {
Remove-Item BackoffFileBackoffFile -Encoding UTF8
Write-Log "Backoff set for ($_.Exception.Message)" -Level ERROR
}
}
Function Test-BackoffActive {
if (-not (Test-Path BackoffFile)) { return false }
try {
lastTry=Get−Date(Get−ConteBackoffFile)
lastTry
if (TunnelBackoffHours) {
TunnelBackoffHours - (true
}
Remove-Item BackoffFile -ErrorAction SilentlyContinue
}
return $false
}
#endregion