I made this script for WireGuard in particular but it can work for OpenVPN if modified slightly.
Basically when the VPN service is running when you are in the office internal servers will NOT be accessible unless you turn off the VPN.
This script attempts to start and stop the VPN based on you location. If you are in the Office it will stop the VPN so you can access internal company resources but when you are away it will turn your VPN on.
Create a text file called WireGuard_Script.bat and paste the following into it and save:
@echo off REM Currently pinging Google's DNS server set IPaddress=126.96.36.199 REM Enter the external IP of your Office LAN set OfficeIP="Your Office External IP" REM The name of the TunnelService set tunnelname=Office REM How many times you want to retry checking for internet set retrycount=20 :networkcheck ping -n 1 %IPaddress% | find "TTL=" if %errorlevel%==0 ( goto IPCheck ) else ( goto wait ) :wait if %retrycount%==0 exit set /a retrycount=%retrycount%-1 ping -n 4 127.0.0.1 >nul goto networkcheck :IPCheck nslookup myip.opendns.com resolver1.opendns.com |find /c %OfficeIP% >C:\temp.txt set /p count=<C:\temp.txt if %count% == 1 net stop WireGuardTunnel$%tunnelname% if %count% == 0 net start WireGuardTunnel$%tunnelname% del C:\temp.txt ipconfig /registerdns net stop WireGuard-Script
I then needed to register this script as a service so it would do it’s thing at startup.
NSSM is a great tool for making this happen.
Once Downloaded I put all the files in the WireGuard installation directory and then ran these commands:
"C:\Program Files\WireGuard\nssm.exe" install WireGuard-Script "C:\Program Files\WireGuard\WireGuard-Script.bat" "C:\Program Files\WireGuard\nssm.exe" set WireGuard-Script start SERVICE_DELAYED_AUTO_START
Once Complete when you open services.msc there is a new service called WireGuard-Script with Automatic Delayed startup type.
I will admit the script is not completely reliable. It may have to do with the retry count possibly I have not tested or troubleshooted anything yet however most of the time it works well.