Skip to content

Instantly share code, notes, and snippets.

@Shterneregen
Last active June 13, 2024 12:12
Show Gist options
  • Select an option

  • Save Shterneregen/a512496243d2d996a50f63f6b2b6de7d to your computer and use it in GitHub Desktop.

Select an option

Save Shterneregen/a512496243d2d996a50f63f6b2b6de7d to your computer and use it in GitHub Desktop.
Windows task to update Cisco AnyConnect InterfaceMetric to help with internet connectivity porblem with running VPN. After the first launch, the task will automatically start when you turn on the VPN
# Create CreateScheduledTask.ps1 file with content below.
# And run as admin command in PowerShell:
# Get-Content .\CreateScheduledTask.ps1 | PowerShell.exe -noprofile -
$taskname="Fix VPN for WSL"
$scriptName = "UpdateAnyConnectInterfaceMetric.ps1"
$commandToUpdateMetric = "Get-NetAdapter | Where-Object {`$_.InterfaceDescription -Match 'Cisco AnyConnect'} | Set-NetIPInterface -InterfaceMetric 5500"
$profilePath = $env:USERPROFILE
$scriptPath = "$profilePath\$scriptName"
if(Test-Path -Path $scriptPath){
Write-Output "File '$scriptPath' already exists"
} else {
New-Item -ItemType File -Path $scriptPath -Value $commandToUpdateMetric
Write-Output "File '$scriptPath' created successfully"
}
$triggerClass = Get-CimClass -ClassName MSFT_TaskEventTrigger -Namespace Root/Microsoft/Windows/TaskScheduler:MSFT_TaskEventTrigger
$trigger = New-CimInstance -CimClass $triggerClass -ClientOnly
$trigger.Subscription =
@"
<QueryList><Query Id="0" Path="Cisco AnyConnect Secure Mobility Client"><Select Path="Cisco AnyConnect Secure Mobility Client">*[System[Provider[@Name='acvpnagent'] and EventID=2039]]</Select></Query></QueryList>
"@
$trigger.Enabled = $True
$triggers = @()
$triggers += $trigger
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 0
$user = Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -expand UserName
$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-Command Get-Content '$scriptPath' | PowerShell.exe -noprofile -"
Register-ScheduledTask -TaskName $taskname -Trigger $triggers -User $user -Action $action -Settings $settings -RunLevel Highest -Force
@mamhadu
Copy link

mamhadu commented Sep 29, 2023

Thanks for sharing the script. This was the best solution I’ve came across so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment