How to make an authenticated web request in Powershell?

前端 未结 3 1952
甜味超标
甜味超标 2020-11-29 21:09

In C#, I might do something like this:

System.Net.WebClient w = new System.Net.WebClient();
w.Credentials = new System.Net.NetworkCredential(username, auth,          


        
3条回答
  •  伪装坚强ぢ
    2020-11-29 21:37

    For those that need Powershell to return additional information like the Http StatusCode, here's an example. Included are the two most likely ways to pass in credentials.

    Its a slightly modified version of this SO answer:
    How to obtain numeric HTTP status codes in PowerShell

    $req = [system.Net.WebRequest]::Create($url)
    # method 1 $req.UseDefaultCredentials = $true
    # method 2 $req.Credentials = new NetworkCredential($username, $pwd, $domain); 
    try
    {
        $res = $req.GetResponse()
    }
    catch [System.Net.WebException]
    {
        $res = $_.Exception.Response
    }
    
    $int = [int]$res.StatusCode
    $status = $res.StatusCode
    return "$int $status"
    

提交回复
热议问题