How to detect an active VPN connection with a specific name

Viewed 14715

I found an article which lists several ways to detect an active VPN:

  1. Using Win32_NetworkAdapter:

    Get-WmiObject -Query "Select * from Win32_NetworkAdapter 
    where Name like '%VPN%' and NetEnabled='True'"
    
  2. Using Win32_NetworkAdapterConfiguration:

    Get-WmiObject -Query "Select * from Win32_NetworkAdapterConfiguration 
    where Description like '%VPN%' and IPEnabled='True'"
    
  3. Checking the presence of an active PPP adapter

    ipconfig | Select-String 'PPP adapter'
    
  4. Checking the IPv4 routing table

    Get-WmiObject -Query "Select * from Win32_IP4RouteTable 
    where Name like '10.0.99.%' or Name like '10.15.99.%'"
    

In my case approaches 1,2 & 4 simply didn't work. The third approach works well and it's really enough. But as far as I understand having multiple VPN connections configured can give an ambiguous result for method 3.

So my questions are:

  1. Is there a way to be more specific (use combined approach maybe?) with method 3, to be able to check the connection name?
  2. Why didn't methods 1 & 2 work for me? Querying it like this

    $adapters = (Get-WmiObject -Query "Select * from Win32_NetworkAdapter")
    foreach($a in $adapters) {
        Write-Host $a.Description
    }
    

    gives me a list of adapter names with no mention of 'VPN' in their description:

    WAN Miniport (SSTP)
    WAN Miniport (IKEv2)
    WAN Miniport (L2TP)
    WAN Miniport (PPTP)
    and so on...
    
4 Answers

Easiest way will be to use the Powershell Commamdlet

Get-VPNconnection -Name "VPN Name"

One of the items reported is "ConnectionStatus". Also if the VPN is an All user connection you will also have to use the switch "-AllUserConnection" with the commandlet

How about using this:

Get-NetAdapter -InterfaceDescription "VPN Name" | where {$_.status -eq "Up"}

Just Use Get-NetAdapter to get a list of the Network/VPN Names..

If you also want to get the PPP-adapter and other hidden adapter info you should use this:

[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()

In my scenario, the presence of TAP in the InterfaceDescription property signifies the VPN connection status, but you could put any string within the test

$NIC = Get-NetIPConfiguration | ? {$_.NetAdapter.status -eq "UP"} | Select-Object InterfaceDescription
    if ($NIC -match "TAP") {
#VPN active → go to work
} else { 
       Write-Host "~~~~~~~~~~~~~~~~~" -ForegroundColor Cyan 
       Write-Host "VPN DEACTIVATED ?" -ForegroundColor Cyan 
       Write-Host "~~~~~~~~~~~~~~~~~" -ForegroundColor Cyan 
    }
Related