Skip to content

Instantly share code, notes, and snippets.

@HandyMenny
Created October 23, 2022 13:01
Show Gist options
  • Save HandyMenny/e3abe01215d1ec5bdaacfa6d5295cc80 to your computer and use it in GitHub Desktop.
Save HandyMenny/e3abe01215d1ec5bdaacfa6d5295cc80 to your computer and use it in GitHub Desktop.
Script to enable/disable wireguard tunnel when IPv4 default gateway changes
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2022-10-23T14:42:10.5827629</Date>
<Author>handymenny</Author>
<URI>\WireguardAutomatic</URI>
</RegistrationInfo>
<Triggers>
<EventTrigger>
<Enabled>true</Enabled>
<Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="Microsoft-Windows-NetworkProfile/Operational"&gt;&lt;Select Path="Microsoft-Windows-NetworkProfile/Operational"&gt;*[System[Provider[@Name='Microsoft-Windows-NetworkProfile'] and EventID=10000]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
</EventTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-18</UserId>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>false</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT1H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>powershell.exe</Command>
<Arguments>-ExecutionPolicy bypass -File C:\wireguardcheck.ps1</Arguments>
</Exec>
</Actions>
</Task>
$homeGateway = "192.168.3.1"
$path = "C:\Program Files\WireGuard\Data\Configurations\"
$config = "profile1"
$tunnelEnabled = !!(wg show $config 2>$null)
$currentGateway = (Get-NetRoute "0.0.0.0/0").NextHop
if ($currentGateway -eq $homeGateway) {
if($tunnelEnabled) {
wireguard.exe /uninstalltunnelservice $config
}
} else {
if(!$tunnelEnabled) {
wireguard.exe /installtunnelservice "$path$config.conf.dpapi"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment