[英]PowerShell Test-Connection “On first response”
我们在公司中使用Citrix,并且有两个地址可以访问Citrix StoreFront:
链接1仅在它们位于内部网络(本地或VPN)上时起作用,链接2仅在它们不在内部网络上时起作用。 这使用户可以猜测他们需要双击桌面上的哪种快捷方式。
为了解决最终用户的困惑,我在下面编写了这个小片段。 它可以按预期运行,但是因为它取决于PING来确定是否可以访问内部服务器来决定...执行速度很慢。
我想做的是在收到PING的响应后立即执行相关的块,而不是等待所有4次PING尝试完成。 在PowerShell中可能吗?
因此,它不是“ PING 4次,如果收到至少一个响应,则运行块 ”,而是“ PING 4次,并在第一个响应运行块 ”。
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)
}
在此先感谢Arbiter
这应该是解决您的问题的好方法:
请注意,我正在使用“ 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")
}
您可以使用-Count 1
测试4次ping,并在ping正常时中断循环:
for($i = 0; $i -lt 4; $i++){
if(Test-Connection -Quiet -ComputerName "8.8.8.8" -Count 1){
$url = "https://external-access.company.com"
$ie = New-Object -com internetexplorer.application
$ie.visible = $true
$ie.navigate($url)
break
}
}
#Script continues
您可以检查测试连接的状态码,例如:
If( (Test-Connection servername -Count 1).StatusCode -eq 0)
但是我建议您在这种情况下只检查一次。 将计数设为1,例如:
Test-Connection -Quiet -ComputerName "8.8.8.8" -Count 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.