Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an authenticated web request in Powershell?

Tags:

powershell

In C#, I might do something like this:

System.Net.WebClient w = new System.Net.WebClient(); w.Credentials = new System.Net.NetworkCredential(username, auth, domain); string webpage = w.DownloadString(url); 

Is there a Powershell version of this, or should I just call through to the CLR?

like image 339
Ry Jones Avatar asked Feb 03 '09 19:02

Ry Jones


People also ask

How do I authenticate in PowerShell?

To sign in interactively, use the Connect-SecMgmtAccount cmdlet. When you run this cmdlet it will open a browser where you will be able to authenticate. If the system you are using to connect does not a browser, then you will be provided a code.

What command would you use to make a request to a web server PowerShell?

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0.

How do I create a Credential object in PowerShell?

Creating credential object There are a few ways that you can create a credential object. The first way to create a credential object is to use the PowerShell cmdlet Get-Credential . When you run without parameters, it prompts you for a username and password. Or you can call the cmdlet with some optional parameters.


2 Answers

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) 
like image 127
Steven Murawski Avatar answered Oct 12 '22 03:10

Steven Murawski


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-Object System.Net.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" 
like image 27
Ralph Willgoss Avatar answered Oct 12 '22 02:10

Ralph Willgoss