如何在Powershell中解压文件?

我有一个.zip文件,需要使用Powershell解压其全部内容。 我正在这样做,但似乎并没有工作:

 $shell = New-Object -ComObject shell.application $zip = $shell.NameSpace("C:\a.zip") MkDir("C:\a") foreach ($item in $zip.items()) { $shell.Namespace("C:\a").CopyHere($item) } 

怎么了? 目录C:\a仍然是空的。

这是一个使用System.IO.Compression.ZipFile的ExtractToDirectory的简单方法:

 Add-Type -AssemblyName System.IO.Compression.FileSystem function Unzip { param([string]$zipfile, [string]$outpath) [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath) } Unzip "C:\a.zip" "C:\a" 

请注意,如果目标文件夹不存在,则ExtractToDirectory将创build它。

如何压缩和提取文件

在PowerShell V5中,内置了一个Expand-Archive命令 (以及Compress-Archive):

 Expand-Archive c:\a.zip -DestinationPath c:\a 

嘿它为我工作..

 $shell = New-Object -ComObject shell.application $zip = $shell.NameSpace("put ur zip file path here") foreach ($item in $zip.items()) { $shell.Namespace("destination where files need to unzip").CopyHere($item) } 

使用expand-archive但是自动创build以归档文件命名的目录:

 function unzip ($file) { $dirname = (Get-Item $file).Basename New-Item -Force -ItemType directory -Path $dirname expand-archive $file -OutputPath $dirname -ShowProgress } 

PowerShell v5.1似乎与v5略有不同。 根据MS文档,它必须有一个-Path参数来指定存档文件path。

 Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference 

否则这可以是如下的实际path,

 Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference 

展开 – 归档文档