How to make an authenticated web request in Powershell?

前端 未结 3 1946
甜味超标
甜味超标 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:35

    The PowerShell is almost exactly the same.

    $webclient = new-object System.Net.WebClient
    $webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
    $webpage = $webclient.DownloadString($url)
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-11-29 21:43

    In some case NTLM authentication still won't work if given the correct credential.

    There's a mechanism which will void NTLM auth within WebClient, see here for more information: System.Net.WebClient doesn't work with Windows Authentication

    If you're trying above answer and it's still not working, follow the above link to add registry to make the domain whitelisted.

    Post this here to save other's time ;)

    0 讨论(0)
提交回复
热议问题