Windows looses Internet Connection after VPN disconnect (Updated with PS script)

Been having issues where sometimes when i disconnected from a VPN in windows, i would end up in a weird state, where windows says it has a connection, but really i cant get to anything outside my local network.

Tried disabling/enabling the NIC, Changing and flushing DNS, etc. with no luck.
Seemed like the only way to get it back up, was to reboot the machine.

Seems like windows sometimes has some issues completely dropping the VPN connection, and you end up in some weird state.

Found this helping answer on a MS forum, that seems to fix the issue, without having to reboot:

Hey all, I was having the same problem on Windows 10. The PPP adapter is not removed after disconnecting from the Windows VPN client and I cannot connect to any ipv4 outside of my local network (still could connect to ipv6 though). I think the primary issue is that the VPN gateway route is not removed from the routing table and therefore is still trying to send ipv4 traffic over the PPP adapter. I fixed this issue by manually setting my primary gateway route for my main network lower than the VPN gateway route. You can do this in cmd cli with "route", or in the Adapter settings:

route CHANGE 0.0.0.0 MASK 0.0.0.0 your.ip.gate.way METRIC 1

https://social.technet.microsoft.com/Forums/office/en-US/efd7c70c-e652-4101-93ac-2c57884e162e/no-internet-access-after-disconnecting-from-vpn#feba9be9-35ac-483b-a6bd-3325e963de7d

Some people also talk about disabling IPv6, haven't tried that yet.

Powershell to the rescue

So after copy pasting the above command a couple of times it got a bit repetitive, so here's a powershell script:

#Get current default gateway
$currentGateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway;
#Make sure we only get ipv4
$currentGatewayIp = ($currentGateway  |  Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value;
#Ask for user input
$gateway = Read-Host 'Default gateway to reset to (enter nothing to use:'$currentGatewayIp')'
if ([string]::IsNullOrEmpty($gateway)) {
    $gateway = $currentGatewayIp;
}
#Fire command!
route CHANGE 0.0.0.0 MASK 0.0.0.0 $gateway METRIC 1
Modding HiTec HS-422 servo for continuous rotation

Modding HiTec HS-422 servo for continuous rotation

Extract 2D drawing from STL using OpenSCAD

Extract 2D drawing from STL using OpenSCAD