我有下面的代码。
$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运行它时,我得到的是401未经授权的。
Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
但是,它在PowerShell 7中运行得很好。我不认为我使用的是5.1中没有的东西;但是为什么它会失败呢?
发布于 2022-09-11 10:50:41
我发现了这个问题,很有趣。我想知道是否有人能解释这件事。所以,在我上面的例子中,这一行是罪魁祸首。
$header = @{"Authorization" = "Basic " + $base64AuthInfo}
在"Basic“中有一个额外的”空格“--由于某种原因,如果我使用PowerShell 7,但在PowerShell 5.1中失败(这是预期的),它运行得很好。删除了额外的空间后,它将在5.1版和7+版上运行。
发布于 2022-09-10 07:21:49
可能是因为PowerShell 5.1发送了这篇博客文章中描述的报头Expect: 100-continue
尝试添加以下调用web请求的方法
if ([Net.ServicePointManager]::Expect100Continue -ne $false) {
[Net.ServicePointManager]::Expect100Continue = $false
}
可以使用以下命令检查每个版本上的设置:
[Net.ServicePointManager]::Expect100Continue
https://stackoverflow.com/questions/73423825
复制相似问题