Skip to main content
 首页 » 编程设计

PowerShell 测试连接 "On first response"

2025年05月04日165三少

我们公司使用Citrix,访问Citrix StoreFront有两个地址:

  1. internal-access.company.com
  2. external-access.company.com

链接 1 仅在它们位于内部网络(本地或 VPN)上时有效,而链接 2 仅在它们不在内部网络上时有效。这让用户猜测他们需要双击桌面上的哪个快捷方式。

为了解决我们最终用户的困惑,我在下面写了这个小片段。它按预期工作,但因为它依赖于 PING 来查看是否可以访问内部服务器来决定...执行速度非常慢。

我想做的是在从 PING 收到响应后立即执行相关 block ,而不是等待所有 4 次 PING 尝试完成。这在 PowerShell 中可行吗?

因此,不是“PING 4 次,如果至少收到 1 个响应,则运行 block ”,而是“PING 4 次,并在第一次响应时运行 block ”。

if(Test-Connection -Quiet -ComputerName "10.10.10.10" -Count 2){ 
 
    $url = "http://internal-access.company.com" 
    $ie = New-Object -com internetexplorer.application;  
    $ie.visible = $true; 
    $ie.navigate($url); 
 
}elseif(Test-Connection -Quiet -ComputerName "8.8.8.8" -Count 4){ 
 
    $url = "https://external-access.company.com" 
    $ie = New-Object -com internetexplorer.application;  
    $ie.visible = $true; 
    $ie.navigate($url); 
 
}else{ 
 
    $wshell = New-Object -ComObject Wscript.Shell 
    $wshell.Popup("Unable to connect to Citrix. Please check your network connection and call the Service Desk on +44(0)207 111 1111 if you require assistance. Thank you.",0,"No network connection detected!",0x1) 
 
} 

提前致谢, 仲裁者

请您参考如下方法:

这应该是您问题的一个很好的解决方案:

请注意,我正在使用 Start-Process 在默认浏览器中启动网页以便于使用。

Function Test-QuickConnection($ip,$count=4,$ttl=50){ 
    $attempts = 0 
    do{ 
        $connected = Test-Connection $ip -Quiet -Count 1 -TimeToLive ([math]::Ceiling(($ttl/$count))) 
    } while ((++$attempts -lt $count) -and !$connected) 
    return $connected 
} 
 
if (Test-QuickConnection "10.10.10.10"){ 
    Start-Process "http://internal-access.company.com" 
} elseif (Test-QuickConnection "8.8.8.8"){ 
    Start-Process "https://external-access.company.com" 
} else { 
    Add-Type -AssemblyName "System.Windows.Forms" 
    [System.Windows.Forms.MessageBox]::Show("Unable to connect to Citrix") 
}