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

后端 未结 8 1464
长发绾君心
长发绾君心 2020-11-28 06:41

What is the equivalent of

curl -u username:password ...

in PowerShell\'s Invoke-RestMethod? I tried this:

$sec         


        
8条回答
  •  情话喂你
    2020-11-28 07:26

    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.

提交回复
热议问题