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?
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.
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.
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.
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)
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With