How to change output of Invoke-WebRequest?

梦想的初衷 提交于 2019-12-25 03:13:36

问题


I want to be able to get the results of Invoke-WebRequest and have my script print either "Failed" if the server was not reached or "Online" if it was reached.

This is what I'm doing to try to do that.

 $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"
 }

I was able to get the script to print "Online" if the server is reached. However when it can't be reached, my script wont print "Failed". Instead it will give me the error:

 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

How can I get the script to print out "Failed" instead of this error message?

Also the $Servers_to_Check variable is multiple servers


回答1:


You need a 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


来源:https://stackoverflow.com/questions/54429748/how-to-change-output-of-invoke-webrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!