如何使用Powershell中的默认凭据运行Web请求

时间:2017-09-13 07:48:57

标签: powershell httpwebrequest

我正在处理以下代码。

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

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

任何人都可以帮助我,因为我想存储一些URL的状态,这个代码工作正常,除了受保护的那些。

1 个答案:

答案 0 :(得分:0)

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

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: -

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

这两个脚本都做得非常好但是如果你想找到许多URL的代码状态,那么你应该选择powershell 3.0,它会以更好的方式处理web请求。

相关问题