Getting a web page using PowerShell is pretty easy using
Invoke-WebRequest
. Getting a web page which is protected using basic authentication isn’t that much harder, but it took me a while to find out how to do that exactly as my initial searches didn’t turn up the right answers.
The trick is that you have to pass in a credential object when you make the call:
$result = Invoke-WebRequest http://foo.com -Credential $credential
That $credential
object is something you have to create. If you don’t pass in an object, you’ll get a prompt btw, which might also be handy.
Creating the object is done like this:
$user = "john.doe"
$password = ConvertTo-SecureString "a_password" -AsPlaintext -Force
$credential = New-Object PSCredential($user, $password)
The PSCredential
object is created and the username and a secure password string is passed into the constructor.
Putting the username and password in your script like this is a bad idea in a lot of cases, so you should really consider if this what you want to do. You can also use the Get-Credential
cmdlet to ask the user for the username and password instead.
That way you keep this sensitive data out of your script and make it more resilient to change as well.
This is all it takes to ask for the credentials and set them into a variable you use later on:
$credential = Get-Credential