如何更改Invoke-WebRequest的输出? [英] How to change output of Invoke-WebRequest?

查看:63
本文介绍了如何更改Invoke-WebRequest的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够获取Invoke-WebRequest的结果,并让我的脚本在服务器未到达时打印"Failed"(失败),或者在服务器到达时显示"Online"(在线).

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

如果可以访问服务器,我能够获得脚本以打印在线".但是,当无法访问它时,我的脚本将不会打印"Failed".相反,它将给我错误:

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?

$ Servers_to_Check 变量是多个服务器

推荐答案

您需要尝试捕获

$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

这篇关于如何更改Invoke-WebRequest的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆