【问题标题】:Piping credential into Invoke-WebRequest将凭证传送到 Invoke-WebRequest
【发布时间】:2019-09-30 19:18:38
【问题描述】:
  • 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,但如果这是根本原因,我不明白为什么两个班轮会起作用。我怀疑我误解了$_ 的评估方式。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你可以用分号来伪造一个“单行”来分隔这样的语句:

    $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 …}
    

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 2016-07-15
      相关资源
      最近更新 更多