You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell VPN自动化脚本If Else语句执行顺序异常求助

PowerShell VPN自动连接脚本问题修复

核心错误点

  • 赋值与比较运算符混淆:PowerShell 中=为赋值运算符,相等判断需使用-eq,原脚本的If语句实际是强制给$Isconnected赋值为字符串"False",永远触发If分支
  • 类型不匹配:VPN-Check返回的是布尔类型的$true/$false,和字符串"True"/"False"的判断结果不符合预期
  • Else语法错误:PowerShell的else后不能直接跟判断条件,需加条件要使用elseif关键字
  • 缺少异常捕获:内部站点无法访问时,GetResponse()会直接抛出异常,不会返回$false,导致脚本直接崩溃

修复后完整代码

function VPN-Check {
    try {
        $HTTP_Request = [System.Net.WebRequest]::Create('https://portal.domain.com/portal/login.jsp')
        $HTTP_Request.Timeout = 5000
        $HTTP_Response = $HTTP_Request.GetResponse()
        $HTTP_Status = [int]$HTTP_Response.StatusCode
        $HTTP_Response.Close()
        return $HTTP_Status -eq 200
    }
    catch {
        return $false
    }
}

function VPN-Connect {
    write-host "Connecting to the VPN..."
    Start-Process "C:\Program Files (x86)\AT&T Global Network Client\NetClient.exe"
    $wshell = New-Object -ComObject wscript.shell
    # 等待窗口激活成功
    while(-not $wshell.AppActivate('AT&T Global Network Client')){
        Sleep 2
    }
    Sleep 5
    1..6 | ForEach-Object {
        $wshell.SendKeys('{TAB}')
        Sleep 1
    }
    $wshell.SendKeys('MyPassw0rd')
    Sleep 1
    $wshell.SendKeys('~')
}

function VPN-Disconnect {
    write-host "Disconnecting from VPN..."
    $wshell = New-Object -ComObject wscript.shell
    if($wshell.AppActivate('AT&T Global Network Client')){
        Sleep 1
        $wshell.SendKeys('~')
        Sleep 1
        $wshell.SendKeys('{TAB}')
        Sleep 1
        $wshell.SendKeys('~')
        Sleep 1
    }
    taskkill /im "NetClient.exe" 2>$null
    net stop "AT&T Network Configuration Service" 2>$null
    net stop "AT&T Global Network Client Service" 2>$null
}

function VPN-Cleanup {
    write-host "Killing the VPN..."
    taskkill /f /im "NetClient.exe" 2>$null
    net stop "AT&T Network Configuration Service" 2>$null
    net stop "AT&T Global Network Client Service" 2>$null
}

$Isconnected = VPN-Check
If (-not $Isconnected) {
    write-host "Connecting to VPN..."
    VPN-Cleanup
    VPN-Connect
}
else {
    write-host "Already connected. Nothing to do"
}

优化点说明

  • 新增VPN-Check异常捕获和5秒超时配置,避免网络不通时脚本直接退出
  • 新增VPN窗口激活重试逻辑,避免客户端启动慢导致按键发送失效
  • 命令后追加2>$null忽略进程/服务不存在时的错误输出
  • 简化重复的TAB按键发送逻辑,可读性更高

内容的提问来源于stack exchange,提问作者Chauncy Peppertooth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:27:04