mardi 29 janvier 2019

How to change output of Invoke-WebRequest?

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

Aucun commentaire:

Enregistrer un commentaire