如何在Powershell中使用默认凭据运行Web请求 [英] How to run a web request using default credentials in Powershell

查看:173
本文介绍了如何在Powershell中使用默认凭据运行Web请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以下代码.

$HTTP_Request =[System.Net.WebRequest]::Create('http://google.com')
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
echo $HTTP_Status

但是我想使用我的默认凭据来运行它,因为很少有返回401的URL,即客户端未获得授权,为此,我需要它使用我的默认凭据来运行.

But I want to run it using my default credentials, because there are few URLs which returns 401 ,that is client not authorized and for that I need it to run using my default credentials.

任何人都可以帮我解决这个问题,因为我想存储某些URL的状态,并且除了受保护的那些代码之外,此代码都可以正常工作.

Can anyone help me regarding same, as I want to store the status of some URLs and this code is working fine except for those which are protected.

推荐答案

所以问题是在使用默认凭据时运行Web请求,这是我找到的解决方案:

So the question was to run web request while using default credentials, here are the solutions I found:

对于Powershell 2.0:-

for powershell 2.0:-

 $req = [system.Net.WebRequest]::Create($uri)
 $req.UseDefaultCredentials = $true
 try
 {
 $res = $req.GetResponse()
 }
 catch [System.Net.WebException]
 {
 $res = $_.Exception.Response
 }
 $int = [int]$res.StatusCode
 echo $int

对于Powershell 3.0:-

For Powershell 3.0:-

try{
$res = Invoke-WebRequest $uri -UseDefaultCredentials 
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
}
$int = [int]$res.StatusCode 
echo $int

两个脚本的运行情况都非常好,但是如果要查找许多URL的代码状态,则应该使用Powershell 3.0,它可以更好地处理Web请求.

Both scripts are extremely doing well but if you want to find code status of many URLs, then you should go for powershell 3.0 , it handles web-requests in a much better way.

这篇关于如何在Powershell中使用默认凭据运行Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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