仅使用PowerShell 5.1调用WebRequest geting 401 Unauthorized



我有以下一段代码。

$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中没有的任何内容;但它为什么会失败呢?

可能是因为PowerShell 5.1发送了标题Expect: 100-continue,如本文中所述

尝试添加以下befure调用web请求

if ([Net.ServicePointManager]::Expect100Continue -ne $false) {
[Net.ServicePointManager]::Expect100Continue = $false
}

您可以使用以下命令检查每个版本的设置:

[Net.ServicePointManager]::Expect100Continue

我发现了这个问题,它非常有趣。我想知道是否有人能解释这一点。所以,在我上面的例子中,这一行是罪魁祸首。

$header = @{"Authorization" = "Basic  " + $base64AuthInfo}

有一个额外的";空间";在";基本"-出于某种原因,如果我使用PowerShell 7,但在PowerShell 5.1中失败,则运行良好(这是意料之中的事(。在我去掉多余的空间后,它在5.1和7+版本上都能运行。

最新更新