kthy
kthy

Reputation: 896

Piping credential into Invoke-WebRequest

I am trying to download a file with the Invoke-WebRequest cmdlet. The file is protected by HTTP basic auth. Doing a two-step like this works:

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

Trying to pipe in the credential so I can do it in a one-liner fails:

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

I've googled the error but the only thing I can find is Invoke-WebRequest using Get method doesn't allow content-body, but if that's the root cause I don't understand why the two-liner would work. I suspect I've misunderstood how $_ is evaluated.

Upvotes: 4

Views: 10778

Answers (1)

Booga Roo
Booga Roo

Reputation: 1781

You can fake a "one-liner" with semicolons used to separate statements like this:

$cred = Get-Credential ; Invoke-WebRequest -Credential $cred -Uri http://example.com/foo.zip -OutFile $env:TEMP\foo.zip

If security isn't an issue you can create the credential without prompts:

$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

As noted, the comment by JosefZ works as well and includes the reason why you can't just pipeline the Get-Credential object into Invoke-Webrequest by itself:

$_ is a pipeline object however -Credential parameter does not accept pipeline input. Use e.g.

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

Upvotes: 3

Related Questions