I am trying to use PowerShell to log into a website and download a file.
However I can't get PS to pass the credentials properly.
Here is my PS:
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential("username","password","domain")
$webpage = $webclient.DownloadString("url goes here")
Here is the log in box I get when I hit the site in IE:
We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.
$cred = Get-Credential without asking for prompts in 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.
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