Get file out from Invoke-Webrequest

This topic contains 4 replies, has 2 voices, and was last updated by  Stig Sörnsen 2 years 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 🙂

You must be logged in to reply to this topic.