简体   繁体   English

使用Powershell Invoke-RestMethod下载大文件?

[英]Downloading large file with Powershell Invoke-RestMethod?

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. 为了自动从特定站点下载文件,该站点要求我向REST Web服务传递JSON对象中包含的一些信息。 In order to do this, I build a hash table, convert it to JSON, then add it to the body of the Invoke-WebRequest. 为此,我构建了一个哈希表,将其转换为JSON,然后将其添加到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. 据我所知,Powershell将响应对象完全加载到内存中,然后再将其最终转储到指定的本地输出路径。 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. 经过一些研究后,看来使用System.Net.WebClient会是最好的选择,因为它会在整个下载过程中缓冲对磁盘的响应。 However, I am at a lost for exactly how to pass a JSON object using this method. 但是,我不知道如何使用此方法传递JSON对象。 Is this possible? 这可能吗? Am I heading down a completely incorrect path? 我要走一条完全错误的道路吗?

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: 请注意,我无法立即对此进行测试,但仅通过在C#中查看此示例即可 ...刺破它可能是这样的:

$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. 再次,只是在黑暗中开枪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM