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

How to run a web request using default credentials in Powershell

我正在编写以下代码。

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

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

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

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

对于 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,它以更好的方式处理网络请求。