如何在Powershell中压缩/解压缩文件?

有没有一种方法可以在PowerShell压缩/解压缩文件(* .zip)?

    DotNetZip将允许你从PowerShell做到这一点。 这不是一蹴而就的,但该库将允许您编写所需的PowerShell脚本。

    您也可以使用COM接口,请参阅使用Windows PowerShell压缩文件,然后打包Windows Vista边栏小工具

    谷歌search“zip powershell”或“unzip powershell”也可能会产生有用的结果。

    这是你如何可以纯粹从Powershell做到的,没有任何外部工具。 这将一个名为test.zip的文件解压缩到当前的工作目录中:

    $shell_app=new-object -com shell.application $filename = "test.zip" $zip_file = $shell_app.namespace((Get-Location).Path + "\$filename") $destination = $shell_app.namespace((Get-Location).Path) $destination.Copyhere($zip_file.items()) 

    现在在.NET Framework 4.5中,有一个ZipFile类可以像这样使用:

     [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') [System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $targetFolder) 

    您可能希望查看PowerShell社区扩展(PSCX) ,它具有特定于此的cmdlet。

    我知道这是一个非常古老的问题,但我只是看到它链接在推特上,我想发表一个当前的答案。

    目前在Windows 10上可用的PowerShell 5或通过Windows Management Framework 5 Production Preview ,带有两个用于“压缩”和“解压缩”的内置cmdlet:

    • 压缩-归档
    • 展开-归档

    我发现最简单的解决scheme就是使用多年来在UNIX环境中使用的infozip二进制文件。

     PS> zip -9r ../test.zip * PS> cd .. PS> unzip -t test.zip Archive: test.zip testing: LinqRepository/ OK testing: LinqRepository/ApplicationService.cs OK testing: LinqRepository/bin/ OK ... No errors detected in compressed data of test.zip. 

    在文本输出中放置一个PowerShell封装将是直接的,但实际上我从来不需要这样做,所以我没有打扰。

    http://www.info-zip.org/

    我也喜欢Info-ZIP (在大多数其他Zip实用程序中find的Zip引擎)和7-Zip ,另一个同时拥有GUI和命令行Zip实用程序的collections夹。 问题是,有一些很好的命令行工具可以用于大多数PowerShell任务。

    运行命令行实用程序时有一些技巧,这些实用程序不是用PowerShell来构build的:

    • 运行名称中以数字开头的可执行文件,以“&”符号作为前缀。

      &7zip.exe

    • 包装每个令牌,实用程序期望从命令行看到,在引号中。

      &“c:\空间path\ SomeCommand.exe”“/参数2”“/参数2”“参数2的值”“值2”

    尝试这个:

     zip filename.zip (Get-ChildItem somepath\*) 

    甚至:

     zip filename.zip (Get-Content ListOfFiles.txt) 

    詹姆斯·霍尔韦尔我喜欢你的答案,但我扩大了一点点

     # Example #unzip "myZip.zip" "C:\Users\me\Desktop" "c:\mylocation" function unzip($fileName, $sourcePath, $destinationPath) { $shell = new-object -com shell.application if (!(Test-Path "$sourcePath\$fileName")) { throw "$sourcePath\$fileName does not exist" } New-Item -ItemType Directory -Force -Path $destinationPath -WarningAction SilentlyContinue $shell.namespace($destinationPath).copyhere($shell.namespace("$sourcePath\$fileName").items()) } 

    WinRAR可以在CMD模式下接受参数

    离子方法岩石:

    https://dotnetzip.codeplex.com/wikipage?title=PS-Examples

    支持密码,其他encryption方法等

    我创build了一个PowerShell 2.0兼容模块,它使用本机Windows操作系统命令以同步方式压缩和解压缩文件。 这适用于较旧的操作系统,如Windows XP,不需要.Net 4.5或任何其他外部工具。 这些函数还会阻止脚本执行,直到文件全部被压缩/解压。 你可以在我的博客上find更多的信息和模块 。