PowerShell 获取旗舰VPN服务器地址并自动添加网络连接

人生第一个PowerShell脚本, 登录旗舰VPN官网并获取最新服务器地址, 批量添加相应的网络连接.

使用方法: 修改username和password, 然后复制代码到PowerShell的REPL程序运行或将代码保存成ps1文件执行.

注意: 受vpn相关的cmdlet限制, 仅支持Windows 8.1和Windows Server 2012 R2.

源代码(2015.01.06更新, 适应新版官网)

$website = 'http://www.qjvpn.com.cn'

$form = @{
    username = $username
    password = $password
    from = ''
}

$res = Invoke-WebRequest "${website}/user/checklogin.php" `
                         -Method 'POST' `
                         -ContentType 'application/x-www-form-urlencoded' `
                         -Body $form `
                         -SessionVariable session

#$res.Content -match 'src="(?<url>\S+)"' > $null
#$url = $Matches.url

#$res = Invoke-WebRequest $url -WebSession session
$res = Invoke-WebRequest "${website}/user/serverlist.php" -WebSession $session
$html = $res.ParsedHtml
$table = $html.getElementsByTagName('table') | ? {$_.className.Contains('sl_selected')}
$trArray = $table.getElementsByTagName('tr')

$dict = @{}
Foreach($tr in $trArray){  
    $tdArray = @()
    foreach($td in $tr.children){
        $tdArray += $td.innerText.Trim()
    }
    $dict['QJ-' + $tdArray[0]] = $tdArray[1]
}

$vpnArray = Get-VpnConnection | ? {$_.Name -match '^QJ-'}
$vpnNameArray = @()

Foreach($vpn in $vpnArray){  
    $name = $vpn.Name
    $vpnNameArray += $name
    If($($dict.Keys) -notcontains $name){
        Remove-VpnConnection $name -Force
    }
}

Foreach($name in $($dict.Keys)){  
    If($vpnNameArray -contains $name){
        Set-VpnConnection $name -ServerAddress $dict[$name]
    }else{
        Add-VpnConnection $name `
                            -ServerAddress $dict[$name] `
                            -TunnelType Pptp `
                            -RememberCredential `
                            -AuthenticationMethod MSChapv2 `
                            -EncryptionLevel Optional
    }
}

$dict | Format-Table