Detect VPN Connection with PowerShell

With Windows 10, it’s pretty easy, you can just use the “Get-VpnConnection” command-let.  However if you are working in an environment that has both Windows 7, Windows 8.1 and Windows 10 machines I would recommend using a WMI query to see if the connection is available.  Below is a PowerShell script I wrote to detect the VPN Connection State.

 


# Written by: Harry Caskey (harrycaskey@gmail.com)
# In this example I used "AnyConnect", "Juniper" or "VPN" as the connection name's, but you can change this to whatever fits your environment.
$vpnCheck = Get-WmiObject -Query "Select * from Win32_NetworkAdapter where (Name like '%AnyConnect%' or Name like '%Juniper%' or Name like '%VPN%') and NetEnabled='True'"
$vpnCheck = [bool]$vpnCheck
#
# Since I converted the variable to a boolean value, it will either be $true or $false. Below is logic to help you when detecting if a connection is available or not.
if ($vpnCheck) {
# If there is a VPN Connection detected...you can write logic here. The $vpnCheck will return $true.
Return $vpnCheck
Exit(0)
}
else {
# If there is no VPN Connection detected...you can write logic here. The $vpnCheck will return $false.
Return $vpnCheck
Exit(1)
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.