使用Powershell的远程Webtest脚本

时间:2019-07-17 12:00:09

标签: powershell

我正在使用Powershell脚本来测试远程计算机上的网站。 该脚本在可用网站上运行良好,但在不可用网站上出现问题。

$HTTP_Request1 = Invoke-command -ComputerName SGEDEEWOSWEBP10  -Scriptblock{Invoke-WebRequest -Method HEAD -Uri www.google.com -UseBasicParsing }

$HTTP_Status1 = $HTTP_Request1.StatusCode
echo $HTTP_Status1 

在google或任何授权的网站上运行良好时,HTTP代码等于200。 但是,当我放置一个未经授权的网站,如www.guns.com时,该网站被网络设备阻止了,我没有HTTP代码,而是一个错误。

错误:

The remote server returned an error: (403) Forbidden.
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
    + PSComputerName        : server name

该网站已被阻止(正常),因此我应该具有403 HTTP代码。

URL                     Protocol   Method   Result  
http://www.guns.com/    HTTP       GET      403 

在服务器上本地使用IE。

Web Page Blocked!
You have tried to access a web page which is in violation of your internet usage policy.

URL: http://www.guns.com/
Category: Weapons (Sales) 
User name: 
Group name:

To have the rating of this web page re-evaluated please click here.

有人可以帮助我获取被拒绝URL的http代码吗?

谢谢。 朱利安

2 个答案:

答案 0 :(得分:0)

添加一个try-catch块,并处理catch中的错误。如果返回了响应,则可以获取如下状态代码:

$ErrorActionPreference = "Stop"

try
{
    $httpRequest = Invoke-command -ComputerName "SGEDEEWOSWEBP10" -Scriptblock { Invoke-WebRequest -Method HEAD -Uri "www.google.com" -UseBasicParsing }
    $httpStatus  = $httpRequest.StatusCode
}
catch
{
    $httpStatus = $_.Exception.Response.StatusCode.value__
}

Write-Host $httpStatus

答案 1 :(得分:0)

感谢您的反馈,我尝试了,但是很遗憾,它没有用。

捕获未检测到错误。

try { $HTTP_Request2 = Invoke-command -ComputerName $IPAddress -Scriptblock{Invoke-WebRequest -Method HEAD -Uri www.guns.com -UseBasicParsing }
$HTTP_Status2 = $HTTP_Request2.StatusCode echo $HTTP_Status2 } 
catch { 
$HTTP_Status2 = $_.Exception.Response.StatusCode.value__ 
echo ko 
      } 
echo $HTTP_Status2

我得到相同的结果,但不显示“ ko”。