Get file out from Invoke-Webrequest

This topic contains 5 replies, has 3 voices, and was last updated by  Mavaddat Javid 2 months, 3 weeks ago.

  • Author
  • #35914

    Stig Sörnsen


    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 🙂

  • #35920

    Dave Wyatt

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

  • #35924

    Stig Sörnsen

    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.

  • #35925

    Dave Wyatt

    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
  • #35927

    Stig Sörnsen

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

  • #97251

    Mavaddat Javid

    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.

You must be logged in to reply to this topic.