0

In order to automate the download of a file from a particular site, the site requires me to pass the REST web service some information contained within a JSON object. In order to do this, I build a hash table, convert it to JSON, then add it to the body of the Invoke-WebRequest.

$hash = @{  logonkey = "$logonkey"; 
        tokenkey = "$tokenkey"
        fileid = "$fileID"
        }

$obj = $hash | convertto-json
$obj = 'obj=' + $obj

Invoke-WebRequest '$url' -Method POST -Body $obj -Outfile $localpath

However, with this method, the rather large file never manages to fully download. Only about half of it is downloaded. From what I can tell, Powershell loads the Response Object fully into memory before finally dumping it to the specified local output path. This has led me to search for a better method, but I am having a very hard time.

After doing a bit of research, it appears that using System.Net.WebClient would be best for this, since it buffers the response to disk throughout the download. However, I am at a lost for exactly how to pass a JSON object using this method. Is this possible? Am I heading down a completely incorrect path?

MisterPuggles
  • 133
  • 1
  • 4
  • 18

1 Answers1

0

Mind you I can't test this right off, but just by looking at an example of this in C#...a stab at it might be something like this:

$hash = @{  logonkey = "$logonkey"; 
        tokenkey = "$tokenkey"
        fileid = "$fileID"
        }

$obj = $hash | convertto-json
$obj = 'obj=' + $obj

$request = New-Object System.Net.WebClient
$request.Headers[HttpRequestHeader.ContentType] = "application/json";
$request.UploadString($url,$obj)

#I would think you could then use the DownloadFile method to pull your file down
$request.DownloadFile($url,$localpath)

Again, just a shot in the dark.

Community
  • 1
  • 1