如何使用7zip解压文件并将其复制到指定位置?

5

我刚刚尝试在PowerShell 中打开一个zip归档文件,并将其中的文件移动到特定的位置,但它总是只移动zip文件夹。我做错了什么?

这是我现在拥有的:

Get-ChildItem C:\zipplayground\*.zip | % {"C:\Program Files (x86)\7-Zip\7zG.exe";
Move-Item $_ C:\unzipplayground\}

如果您的问题没有提到,为什么您的主题引用不使用开源DLL呢? - alroc
4个回答

11

我认为正确的答案应该是这样的:

Get-ChildItem C:\zipplayground\*.zip | % {& "C:\Program Files\7-Zip\7z.exe" "x" $_.fullname "-oC:\unzipplayground"}

Alroc几乎是正确的,但在引号中使用$_.fullname无法正常工作,并且他错过了7z的-o参数。我使用的是7z.exe而不是7zg.exe,这样可以正常工作。

有关命令行帮助,请参见此处:http://sevenzip.sourceforge.jp/chm/cmdline/。基本上,x代表“解压缩”,-o代表“输出目录”。


是的,谢谢 :) 唯一不同的是我的7zip路径。 - RayofCommand
在路径之前,"-o" 是什么意思? - RayofCommand
这是用于输出目录的7z参数。它必须“附加”到路径上,不允许有空格。 - Poorkenny

4

获取7z.exe文件路径的函数

function Get-7ZipExecutable
{
    $7zipExecutable = "C:\Program Files\7-Zip\7z.exe"
    return $7zipExecutable
}

用于将文件夹压缩为zip格式的函数,其中目标位置已设置

function 7Zip-ZipDirectories
{
    param
    (
        [CmdletBinding()]
        [Parameter(Mandatory=$true)]
        [System.IO.DirectoryInfo[]]$include,
        [Parameter(Mandatory=$true)]
        [System.IO.FileInfo]$destination
             )

    $7zipExecutable = Get-7ZipExecutable

     # All folders in the destination path will be zipped in .7z format
     foreach ($directory in $include)
    {
        $arguments = "a","$($destination.FullName)","$($directory.FullName)"
    (& $7zipExecutable $arguments)

        $7ZipExitCode = $LASTEXITCODE

        if ($7ZipExitCode -ne 0)
        {
            $destination.Delete()
            throw "An error occurred while zipping [$directory]. 7Zip Exit Code was [$7ZipExitCode]."
        }
    }

    return $destination
}

解压文件的函数

function 7Zip-Unzip
{
    param
    (
        [CmdletBinding()]
        [Parameter(Mandatory=$true)]
        [System.IO.FileInfo]$archive,
        [Parameter(Mandatory=$true)]
        [System.IO.DirectoryInfo]$destinationDirectory
    )

    $7zipExecutable = Get-7ZipExecutable
    $archivePath = $archive.FullName
    $destinationDirectoryPath = $destinationDirectory.FullName

    (& $7zipExecutable x "$archivePath" -o"$destinationDirectoryPath" -aoa -r)

    $7zipExitCode = $LASTEXITCODE
    if ($7zipExitCode -ne 0)
    {
        throw "An error occurred while unzipping [$archivePath] to [$destinationDirectoryPath]. 7Zip Exit Code was [$7zipExitCode]."
    }

    return $destinationDirectory
}

感谢Nithin K Anil的组织。 - Faizaan Khan

0

我没有7Zip来测试,但我认为它失败是因为你没有告诉7Zip要操作什么,而且你自己将ZIP文件移动到目标位置。试试这个:

Get-ChildItem C:\zipplayground\*.zip | % {invoke-expression "C:\Program Files (x86)\7-Zip\7zG.exe x $_.FullName c:\unzipplayground\";}

在表达式或语句中出现了意外的标记'x'。请问应该用什么代替x?抱歉我是新手。谢谢。 - RayofCommand
x 是正确的,你需要它来提取zip文件。这是在Powershell中调用程序时的语法问题,我目前没有任何测试工具。我认为你需要移动引号。尝试使用我的编辑。 - alroc
就我在下面的答案中提到的,双引号之间的 "$_.fullname" 是不可行的,解析器无法解析变量成员。 - Poorkenny

0
如果您想避免使用像7zip这样的开源exe/dll文件,则可以安装Powershell的PSCX模块,并使用expand-archive命令。请注意,PSCX的最低要求是.net 4(我使用的是4.5)和powershell 3.0。

http://pscx.codeplex.com/


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