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

后端 未结 8 1473
长发绾君心
长发绾君心 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:14

    This version works with Get-Credential's PSCredential object. It also works cross-platform in PowerShell 6.0. It does this by avoiding use of BSTR calls, which are sometimes suggested when attempting to extract the password from PSCredential.

    $creds = Get-Credential
    $unsecureCreds = $creds.GetNetworkCredential()
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $unsecureCreds.UserName,$unsecureCreds.Password)))
    Remove-Variable unsecureCreds
    
    Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} ...
    

提交回复
热议问题