Powershell Regex find name VPN connection

Alexey 1 Reputation point
2023-05-25T11:12:45.0566667+00:00
Hi all ) please need a help, I have a scipt to disconnect VPN (powershell):

$vpnName = "MyVPN";
$vpn = Get-VpnConnection -Name $vpnName;

if($vpn.ConnectionStatus -eq "Connected"){
  rasdial $vpnName /DISCONNECT;
}

Please tell me, how I can find and set var $vpnName if I know just part of VPN name, like "vash", full VPN name maybe VPNvashinsider or VPN vashinsider or vpnvashinsider.com

I need regex how I can set var $vpnName taked from part of word "vash"? Thanks a lot!
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,466 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 46,556 Reputation points
    2023-05-25T15:46:21.7533333+00:00

    Something like this might work for you:

    $vpnName = "MyVPN";
    
    [array]$vpns = Get-VpnConnection |
                Where-Object {$_.Name -Like "*$vpnName" -AND $_.ConnectionStatus -eq "Connected"}
    
    if ($vpns.count -eq 1){
        rasdial $vpnName /DISCONNECT
    }
    else{
        Write-Host "Multiple, or no, ($($vpns.count)) VPN connections match '$vpnName'"
        $vpns.Name
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.