Removing Insecure Wireless Connections with PowerShell

Fri, Jun 7, 2013 2-minute read

Troy Hunt recently posted a great discussion about the dangers of letting your devices automatically connect to insecure wireless networks – especially if those have a common name like ‘Starbucks’ or ‘Apple Demo’.

All devices let you “forget” a network when you are in range, and Windows 7 (and before) even had an interface that let you delete networks when they were out of range.

This dialog was removed in Windows 8, although the ‘netsh’ command still lets you accomplish it from the command line.

To fill this gap, a bunch of tools have sprung up, and Scott Hanselman just threw his hat into the ring, too. He wrote a custom C# app (“WiFi.exe”), even mentioning “I could have used PowerShell or something…”.

If you wanted to go the PowerShell route, what would that look like? And not just deleting specified networks, but automatically deleting all insecure ones (Automatic, no password).

Quite simple, in fact.

After a few helper functions, it’s just “Get-UnsecureWlanProfile | Remove-WlanProfile”.

function Get-WlanProfile
{
    $conn = [Ordered] @{}
    netsh wlan show all | % {
        if($_ -match "^[\s]+(Name|Authentication|Connection Mode)\s+:")
        {
            if($_ -match "Name")
            {
                if($conn.Name -and $conn.Authentication -and $conn."Connection Mode")
                {
                    [PSCustomObject] $conn
                }
                $conn = [Ordered] @{}
            }
           
            $label,$value = $_ -split ':'
            $conn[$label.Trim()] = $value.Trim()
        }
    }
}
function Get-UnsecureWlanProfile
{
    Get-WlanProfile | ? {
        ($_.Authentication -eq 'Open') -and
        ($_."Connection mode" -match "automatically")
    }
}

function Remove-WlanProfile
{
    param(
        [Parameter(ValueFromPipelineByPropertyName)]
        $Name
    )

    netsh wlan delete profile name="$Name"
}

If that’s too verbose for you, here is an alternative version as a one-liner:

netsh wlan export profile | ? { $_ } | % { $f = $_ -replace '.*"(.\\.*.xml)".*','$1'; $w = [xml] (gc $f -raw); if(($w.WLANProfile.MSM.security.authEncryption.authentication -eq 'Open') -and ($w.WLANProfile.connectionMode = 'Automatic')) { netsh wlan delete profile name="$($w.WLANProfile.Name)" }; ri $f }