Get-WifiPassword.psm1

#requires -version 3

function Get-WifiPassword
{
    [CmdletBinding(DefaultParameterSetName='NoParam')]
    param (
        [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, ParameterSetName='ParamExists')]
        [string[]]$NetworkName,
        [switch]$OnlyExisting)

    begin
    {
        $noParam = $PSCmdlet.ParameterSetName -eq 'NoParam'
        if ($noParam)
        {
            $names = netsh wlan show profiles |select-string -Pattern ':\s(?<name>.*)$' | %{$_.Matches.Groups} |? Name -eq name | select -ExpandProperty value
        }
    }
    
    process
    {
        if ($noParam)
        {
            foreach ($name in $names)
            {
                Get-WifiPasswordInternal -Name $name | ? {-not $OnlyExisting -or ($OnlyExisting -and $_.Password) }
            }

            return
        }

        $NetworkName | %{ Get-WifiPasswordInternal $_ }
    }

}

Export-ModuleMember -Function Get-WifiPassword

function Get-WifiPasswordInternal
{
    param([parameter(Mandatory=$true)][string]$Name)

    $profileStrings = netsh wlan show profiles name="$name" key=clear
    if ($profileStrings | Select-String 'not found' -Quiet)
    {
        Write-Warning "Name $name unexpectedly not found"
        continue
    }

    $profileData = $profileStrings | Out-String
    if ($profileData -match '(?m)(Security key\s*: Present\s*Key Content\s*: (?<password>.*)$)|(Security key\s*: Absent)')
    {
        [pscustomobject]@{Name = $name;Password = $Matches.password}
    }
}