我尝试使用 Invoke-WebRequest 下载一个 zip 文件,并即时将其提供给 Extract-Archive。我并不完全热衷于在此过程中不使用磁盘(不过这样做会很好),但如果出现临时文件,最好让它在进程结束后消失。我尝试了这个命令(以及几个类似的命令):
Invoke-WebRequest https://github.com/PowerShell/PowerShell/releases/download/v6.0.0-beta.8/PowerShell-6.0.0-beta.8-win-x64.zip | Extract-Archive -DestinationPath C:\Kellekek\Microsoft\PowerShell\6.0.0-beta.8
但下载完成后它就挂了。是我操作错误还是 PS Core 出了问题?
答案1
你做错了。Invoke-WebRequest
返回一个类型的对象WebResponseObject
。该对象具有以下属性:
$x |get-member
TypeName: Microsoft.PowerShell.Commands.WebResponseObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
BaseResponse Property System.Net.WebResponse BaseResponse {get;set;}
Content Property byte[] Content {get;set;}
Headers Property System.Collections.Generic.Dictionary[string,string] Headers {get;}
RawContent Property string RawContent {get;set;}
RawContentLength Property long RawContentLength {get;}
RawContentStream Property System.IO.MemoryStream RawContentStream {get;}
StatusCode Property int StatusCode {get;}
StatusDescription Property string StatusDescription {get;}
Content
听起来很有希望。您可以尝试将其与 一起使用Extract-Archive
,但我无法尝试,因为我的 PowerShell 不认识此 cmdlet,而且我不知道您从哪里获得它。
那将是:
(Invoke-WebRequest https://your/url/...).Content | Extract-Archive -DestinationPath C:\Kellekek\Microsoft\PowerShell\6.0.0-beta.8
如果这不起作用,您可以使用临时文件,如下所示:
# Create a new temporary file
$tmp = New-TemporaryFile
# Store the download into the temporary file
Invoke-WebRequest -OutFile $tmp https:/.....
# extract the temporary file (again, this is untested)
$tmp | Extract-Archive
# remove temporary file
$tmp | Remove-Item
答案2
必须调整杰拉尔德的答案才能使其发挥作用:
# create temp with zip extension (or Expand will complain)
$tmp = New-TemporaryFile | Rename-Item -NewName { $_ -replace 'tmp$', 'zip' } –PassThru
#download
Invoke-WebRequest -OutFile $tmp $url
#exract to same folder
$tmp | Expand-Archive -DestinationPath $PSScriptRoot -Force
# remove temporary file
$tmp | Remove-Item