Author Posts

March 2, 2016 at 3:07 am

Hi,

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 🙂

March 2, 2016 at 5:24 am

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

March 2, 2016 at 6:05 am

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.

March 2, 2016 at 6:09 am

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

March 2, 2016 at 6:15 am

@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 🙂

March 28, 2018 at 3:51 am

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 = "https://github.com/$((Invoke-WebRequest -Uri "http://github.com/bruderstein/nppPluginManager/releases/latest").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 ~\npppm.zip -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

Expand-Archive

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