Invoke-WebRequest在PowerShell 5.1报401未授权,PowerShell 7正常
PowerShell 5.1调用Invoke-WebRequest报401未授权,PS7却正常?
问题情况
我写了这段PowerShell代码:
$email = "email@example.com" $token = "tokentokentoken" $inputUrl = 'https://example.com/url' $outfile = 'output.txt' $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $email,$token))) $header = @{"Authorization" = "Basic " + $base64AuthInfo} Invoke-WebRequest -Method Get -Headers $header -Uri $url -OutFile $outfile
在PowerShell 5.1里运行会返回:
Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
但换PowerShell 7运行完全没问题,我没用到PS5.1不支持的特性,这是为啥?
问题根源
- Authorization头的多余空格:你代码里写的是
"Basic "(两个空格),但HTTP规范里Basic和后面的凭证字符串之间只需要一个空格。PowerShell 7会自动修正HTTP头里的多余空格,但PS5.1会原封不动把带双空格的头发送出去,有些严格遵循规范的服务器不认这种格式,直接返回401。 - 变量名笔误(可忽略,但需确认):代码里定义的是
$inputUrl,但调用Invoke-WebRequest时用的是$url——不过你说PS7正常,说明实际运行的代码里变量名是统一的,这个应该不是问题。
解决办法
最简单的就是把双空格改成单空格:
$header = @{"Authorization" = "Basic " + $base64AuthInfo} # 只留一个空格
或者直接用PowerShell内置的凭证方式,不用自己拼接Authorization头,PS5.1和PS7都兼容:
$credential = New-Object System.Management.Automation.PSCredential ($email, (ConvertTo-SecureString $token -AsPlainText -Force)) Invoke-WebRequest -Method Get -Credential $credential -Uri $inputUrl -OutFile $outfile
内容的提问来源于stack exchange,提问作者NFR
相关产品推荐
相关产品推荐

