Get file out from Invoke-Webrequest

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Stig Sörnsen Stig Sörnsen 9 months, 1 week ago.

  • Author
    Posts
  • #35914
    Profile photo of Stig Sörnsen
    Stig Sörnsen
    Participant

    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 🙂

  • #35920
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

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

  • #35924
    Profile photo of Stig Sörnsen
    Stig Sörnsen
    Participant

    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
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    Profile photo of Stig Sörnsen
    Stig Sörnsen
    Participant

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