将凭证插入Invoke-WebRequest

时间:2019-09-27 12:32:23

标签: powershell

  • 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,但是如果这是根本原因,我不明白为什么两层衬套会起作用。我怀疑我误解了$_的评估方式。

1 个答案:

答案 0 :(得分:2)

您可以使用分号来伪造“单线”,用分号分隔这样的语句:

$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的原因:

  

$ _是管道对象,但是-Credential参数不接受   管道输入。使用例如

Get-Credential | ForEach-Object {Invoke-WebRequest -Credential $_ -Uri …}