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

时间:2013-08-02 11:09:34

标签: powershell 7zip

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

这就是我现在所拥有的:

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

4 个答案:

答案 0 :(得分:7)

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

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代表'eXtract',-o代表'输出目录'

答案 1 :(得分:2)

获取7z.exe路径的功能

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

将目标设置为

的文件夹压缩的功能
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
}

答案 2 :(得分:0)

我没有7Zip进行测试,但我认为它失败了,因为你没有告诉7Zip要操作什么,而你正在自己将ZIP文件移动到目的地。试试这个:

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

答案 3 :(得分:0)

如果你想避免像7zip这样的开源exe / dll,那么为powershell安装PSCX模块并使用expand-archive。请注意,PSCX要求至少为.net 4(我使用4.5)和powershell 3.0

http://pscx.codeplex.com/