PowerShell's Invoke-RestMethod equivalent of curl -u (Basic Authentication)

This is the only method that worked for me so far:

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} ...

But I don't believe there isn't a better way.


I'm not sure why the -Credential parameter isn't working in your case, but it works with the httpbin service.

You can try this:

$pwd = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ('PsUser', $pwd)

Invoke-RestMethod 'http://httpbin.org/basic-auth/PsUser/MyPassword' -cred $cred

Edit: As noted in the comments, this method will not send the Authorization header on the initial request. It waits for a challenge response then re-sends the request with the Authorization header. This will not work for services that require credentials on the initial request.