- PowerShell 5.1.17763.592/Windows Server 2019 版本 1809(内部版本 17763.737)
我正在尝试使用 Invoke-WebRequest
cmdlet 下载文件。该文件受 HTTP 基本身份验证保护。像这样分两步进行:
PS E:\> $cred = Get-Credential
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
PS E:\> Invoke-WebRequest -Uri http://example.com/foo.zip -Credential $cred -OutFile $env:TEMP\foo.zip
尝试通过管道输入凭据以便我可以在一行中完成它失败了:
PS E:\> Get-Credential | Invoke-WebRequest -Uri http://example.com/foo.zip -Credential $_ -OutFile $env:TEMP\foo.zip
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
Invoke-WebRequest : Cannot send a content-body with this verb-type.
At line:1 char:18
+ ... redential | Invoke-WebRequest -Uri http://example.com/foo.z ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], ProtocolViolationException
+ FullyQualifiedErrorId : System.Net.ProtocolViolationException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
我用谷歌搜索了这个错误,但我唯一能找到的是 Invoke-WebRequest using Get method doesn't allow content-body ,但如果这是根本原因,我不明白为什么双线会起作用。我怀疑我误解了 $_
的计算方式。
最佳答案
你可以用分号来伪造一个“单行”来分隔语句,如下所示:
$cred = Get-Credential ; Invoke-WebRequest -Credential $cred -Uri http://example.com/foo.zip -OutFile $env:TEMP\foo.zip
如果安全不是问题,您可以在没有提示的情况下创建凭据:
$User = "whatever"
$Pass = ConvertTo-SecureString -String "plaintextpassword" -Force -AsPlainText
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $Pass
Invoke-WebRequest -Credential $Cred -Uri http://example.com/foo.zip -OutFile $env:TEMP\foo.zip
如前所述,JosefZ 的评论同样有效,其中包括为什么您不能将 Get-Credential
对象单独通过管道传输到 Invoke-Webrequest
中的原因:
$_ is a pipeline object however -Credential parameter does not accept pipeline input. Use e.g.
Get-Credential | ForEach-Object {Invoke-WebRequest -Credential $_ -Uri …}
关于powershell - 将凭据管道传输到 Invoke-WebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58134638/