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

如何在PowerShell脚本循环中检测URL响应,异常时切换本地HTML?

实现PowerShell脚本的URL状态检测与页面切换

以下是修改后的完整脚本,加入了HTTP响应检测逻辑,会自动在远程URL异常时切换到本地HTML文件,恢复正常后切回远程页面:

# 配置参数
$viewer = "chrome.exe"
$remoteUrl = "https://192.168.1.1"
$localHtmlPath = "file:///C:/path/to/your/local/page.html"  # 替换为实际本地HTML路径
$checkIntervalSeconds = 10  # 检测间隔,单位:秒
$currentPage = "remote"  # 记录当前显示的页面状态:remote 或 local

# 启动Chrome并打开远程URL
Start-Process -FilePath $viewer -ArgumentList '--ignore-certificate-errors --incognito --kiosk "$remoteUrl"'

# 等待Chrome进程启动
do {
    $processHMI = Get-Process chrome -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 1
} until ($processHMI -ne $null)

# 持续检测URL状态并切换页面
while ($processHMI -ne $null) {
    try {
        # 发送HTTP请求检测远程URL状态,忽略SSL证书错误
        $response = Invoke-WebRequest -Uri $remoteUrl -UseBasicParsing -IgnoreSslCertificateErrors -TimeoutSec 5
        
        # 如果响应正常,且当前是本地页面,则切回远程URL
        if ($currentPage -eq "local") {
            Switch-ChromePage $remoteUrl
            $currentPage = "remote"
            Write-Host "远程URL恢复正常,切回页面:$remoteUrl"
        }
    } catch {
        # 请求异常(连接失败、超时、HTTP错误等),如果当前是远程页面,则切换到本地HTML
        if ($currentPage -eq "remote") {
            Switch-ChromePage $localHtmlPath
            $currentPage = "local"
            Write-Host "远程URL异常,切换到本地页面:$localHtmlPath"
        }
    }

    # 更新进程状态,等待下一次检测
    $processHMI = Get-Process chrome -ErrorAction SilentlyContinue
    Start-Sleep -Seconds $checkIntervalSeconds
}

# 切换Chrome页面的函数(通过模拟键盘操作实现)
function Switch-ChromePage {
    param([string]$targetUrl)
    
    # 激活Chrome窗口(kiosk模式下Chrome应为当前窗口,若不是可调整窗口标题匹配)
    $chromeWindow = Get-Process chrome | Select-Object -First 1 -ExpandProperty MainWindowHandle
    [void][System.Windows.Forms.SendKeys]::SendWait("%{TAB}")  # 切换到Chrome窗口(按需调整)
    Start-Sleep -Seconds 0.5
    
    # 调出地址栏,输入目标URL并回车
    [void][System.Windows.Forms.SendKeys]::SendWait("^l")  # Ctrl+L 选中地址栏
    Start-Sleep -Seconds 0.3
    [void][System.Windows.Forms.SendKeys]::SendWait("$targetUrl{ENTER}")
    Start-Sleep -Seconds 1
}

关键说明:

  1. 参数配置:根据实际情况修改$remoteUrl、$localHtmlPath和$checkIntervalSeconds,本地HTML路径需用file:///开头(注意三个斜杠)。
  2. HTTP检测逻辑:使用Invoke-WebRequest发送请求,通过-IgnoreSslCertificateErrors忽略证书错误,-TimeoutSec设置超时时间避免长时间等待;捕获所有请求异常(包括连接失败、超时、4xx/5xx状态码)。
  3. 页面切换实现:通过Send-Keys模拟键盘操作,在kiosk模式下用Ctrl+L调出地址栏,输入目标地址后回车;函数Switch-ChromePage封装了这一逻辑。
  4. 状态跟踪:用$currentPage变量记录当前显示的页面类型,避免重复切换操作,减少不必要的窗口干扰。
  5. 循环检测:只要Chrome进程存在,就会持续执行检测逻辑,进程关闭后循环终止。

内容的提问来源于stack exchange,提问作者Andrii Shyrokov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 06:20:10