How to login to website with basic authentication using Powershell

This is what I got to work. I believe the key part is the "Basic" in the CredentialCache

$webclient = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential("un","pw")
$credCache.Add("url", "Basic", $creds)
$webclient.Credentials = $credCache
$webpage = $webclient.DownloadString("url")

If you want to use Invoke-WebRequest instead of the WebClient:

$securepassword = ConvertTo-SecureString "password" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential("username", $securepassword)
Invoke-WebRequest -Uri "url goes here" -Credential $credentials

I based the code on this blog article by Douglas Tarr. Note that in the article the username and password are confused, but I've fixed them in my sample.

Tags:

Powershell