在PowerShell中使用7z解压文件

16

如何在PowerShell中使用7z命令解压缩文件?

set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
sz x  $zipfilePath $destinationUnzipPath -aoa -r;

命令可以正常运行,但它说“没有文件需要处理,一切都好”,而不是解压文件?


1
事后看来:唯一的问题是7z.exe命令的语法 - 从_PowerShell_(通过别名)调用7z是次要的。 - mklement0
谢谢,我想测试一个zip文件。你的答案让我有了起点。 第一行:sz t $zipfile 第二行:echo $LASTEXITCODE #成功为0,否则请参考http://7zip.bugaco.com/7zip/MANUAL/exit_codes.htm - JohnC
5个回答

11

下面这个命令最终解决了我的问题:sz x -o$destinationUnzipPath $zipfilePath -r ;


9

我不想使用别名、函数或Start-Process。在网上搜索了一下之后,我找到了这个宝石(但我不记得是在哪里找到的):

& ${env:ProgramFiles}\7-Zip\7z.exe x $zipfilePath "-o$($destinationUnzipPath)" -y

如果你不想看到7z的信息,可以在结尾处添加 > $null


1
谢谢,这帮助我解决了这个已知的 bug:https://github.com/PowerShell/Microsoft.PowerShell.Archive/issues/69 - Nicolas Rouquette
谢谢,这个在PowerShell终端上可以工作;但是不能在YML脚本文件上运行。 - Steven Lee

8

有了7zip PowerShell模块,现在就很轻松。

#   Install 7zip module

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Set-PSRepository -Name 'PSGallery' -SourceLocation "https://www.powershellgallery.com/api/v2" -InstallationPolicy Trusted
Install-Module -Name 7Zip4PowerShell -Force

#   Extract 7zip file

$sourcefile = "c:\source\sample.7z"
Expand-7Zip -ArchiveFileName $sourcefile -TargetPath 'c:\destinaation'

如果有人需要一个在 Windows 7、Windows 8 & 8.1、Windows 10 上像钟表一样工作的代码,那么这个是正确的选择;微软的 .Net 版本在一些较老的 Windows 操作系统上不可靠。顺便说一句,这也是 chocolatey 包管理器(chocolatey.org)使用的! - jiciftw

1

我的使用情况略有不同,因为我有一个需要解压的目录中有多个tar文件。我分享这个命令是因为相同的命令也可以被使用或稍作修改后被使用:

以下是在Windows 10上通过Powershell对我有效的命令:

注意:您需要根据自己的用例更改下面的路径。

$srcFolderPathWithTar="C:\SomeFilder\has\multiple\tar\files"
$targ="C:\Users\your_user_name\Downloads\new" 

. "C:\Program Files\7-Zip\7z.exe"  x "-o$($targ)" "$srcFolderPathWithTar" -r -y;

0

我使用了包含路径的"fullname"
此外,我不得不在PowerShell中更改目录到提取数据的输出目录,即D:\temp

我拒绝相信在这个时代将一堆文件从不同的文件夹复制或提取到单个位置是一项复杂的任务。

$rars = (Get-ChildItem "D:\Path\To\folder" -Recurse *.rar).fullname
foreach ($rar in $rars) {& "C:\Program Files\7-Zip\7z.exe" e $rar}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接