What is the equivalent of
curl -u username:password ...
in PowerShell\'s Invoke-RestMethod? I tried this:
$sec
I've found that using the -WebSession parameter works, if you pre-create a WebRequestSession object with credentials. I won't rehash how to create a PS Credential object, as that's already been covered in other answers.
$WebSession = New-Object -TypeName Microsoft.PowerShell.Commands.WebRequestSession -Property @{Credentials=$Credential}
Invoke-RestMethod -Uri "your_URI" -WebSession $WebSession
This approach sends the auth header on the first call, so avoids the 401 response.
Incidentally, this approach can also be used to set proxy details (which don't work properly in all versions of PS when specified using the parameters), and handles cookies if your API requires that.