Get file out from Invoke-Webrequest


I am playing around with Web API and returning octet-stream for file download.
I was just wondering if there is no way to get the filestream when saving the ‘iwr’ in a variable?

This works:

Invoke-WebRequest $url -ContentType “application/json” -OutFile C:\temp\test.txt

But I can’t manage to get the file out if I save the ‘iwr’ in a variable?

$request = Invoke-WebRequest $url -ContentType “application/json”

Just because I’m curious :slight_smile:

What’s in your $request.Content property at that point? JSON text, or something else?

Hi Dave,

I have a byte array:

PS C:> $req.Content | gm
TypeName: System.Byte

I have tried to loop through every property/method I could fine.

That’s perfect. With a byte array, you can write to a file:

Set-Content -Path C:\temp\test.txt -Encoding Byte -Value $request.Content

@Dave, totally awesome! Couldn’t figure out to specify the encoding.

Tried this:

$req.Content > C:\temp\test.txt but that - ofcourse - just printet out the bytes in plain text.

Thanks :slight_smile:

I like this. Is there an easy way to keep the file in memory instead of writing it to disk? I am using the following directives to download a ZIP file, but I would like to keep the file in memory instead of writing it to disk (just for my own satisfaction).

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$npppm = "$((Invoke-WebRequest -Uri "").ParsedHtml.getElementsByTagName('li') | Where-Object {$_.className -eq 'd-block py-2'} | ForEach-Object { $_.getElementsByTagName('a') } |  Where-Object { $_.pathName -match "^.*?x64.*" } | Select-Object -Expand pathName)"
Set-Content -Path ~\ -Encoding Byte -Value (Invoke-WebRequest -Method Get -Uri $npppm).Content

So instead of Set-Conent writing to disk, it would just output the byte value so I could keep it in a PowerShell variable. Or even, I could pipe the result to

so that it writes the contents to disk without ever having the ZIP stored.