Powershell 如何更改Invoke WebRequest的输出?
我希望能够获得Invoke WebRequest的结果,并在未到达服务器时打印“失败”,或者在到达服务器时打印“联机” 这就是我试图做到的Powershell 如何更改Invoke WebRequest的输出?,powershell,if-statement,httprequest,Powershell,If Statement,Httprequest,我希望能够获得Invoke WebRequest的结果,并在未到达服务器时打印“失败”,或者在到达服务器时打印“联机” 这就是我试图做到的 $IW_Results = $Servers_to_Check | ForEach-Object { Invoke-WebRequest -Uri $_ } $err = $IW_Results | ?{$_.gettype().Name -eq "ErrorRecord"} if($err){ Write-Output "Failed" }
$IW_Results = $Servers_to_Check | ForEach-Object { Invoke-WebRequest -Uri $_ }
$err = $IW_Results | ?{$_.gettype().Name -eq "ErrorRecord"}
if($err){
Write-Output "Failed"
}
else {
Write-Output "Online"
}
我能够得到脚本打印“在线”如果服务器是达到。但是,当无法访问时,我的脚本不会打印“失败”。相反,它会给我一个错误:
Invoke-WebRequest : Unable to connect to the remote server
At C:\Users\admin\Documents\VM-scripts\VM-tester.ps1:32
char:52
+ ... ts = $Servers_to_Check | ForEach-Object { Invoke-WebRequest -Uri $_ }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:Htt
pWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe
ll.Commands.InvokeWebRequestCommand
如何让脚本打印“失败”而不是此错误消息
另外,
$Servers\u to\u Check
变量是多个服务器您需要一个Try Catch
$Servers_to_Check = "google.com", "asdasdf.asdfaa.sdf","yahoo.com"
$IW_Results = $Servers_to_Check | ForEach-Object {
try{
Invoke-WebRequest -Uri $_ | Out-Null
"Online"
}catch{
"Failed"
}
}
$IW_Results
研究如何使用
try/catch
结构。[grin]你需要在IWR调用上设置ErrorAction以使该捕获生效吗?我不这么认为。你说得很对!我崩溃了,并且[喘息!arg!]测试了它。。。[咧嘴笑]