Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unzip a file and copy it to specific location with 7zip?

I just tried to open a zip archive in powershell and move the files in it to a specific location. but it always moves just the zip folder. What am I doing wrong ?

This is what I have now :

Get-ChildItem C:\zipplayground\*.zip | % {"C:\Program Files (x86)\7-Zip\7zG.exe";
Move-Item $_ C:\unzipplayground\}
like image 384
RayofCommand Avatar asked Aug 02 '13 11:08

RayofCommand


2 Answers

I believe the right answer should be something like that:

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

Alroc was almost right, but $_.fullname between quotes doesn't work, and he was missing the -o parameter for 7z. I'm using 7z.exe instead of 7zg.exe, works fine this way.

For reference, the command line help can be found here: http://sevenzip.sourceforge.jp/chm/cmdline/ Basically, x stands for 'eXtract' and -o for 'Output directory'

like image 73
Poorkenny Avatar answered Nov 12 '22 12:11

Poorkenny


Function to acquire path of the 7z.exe

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

Function to zip folders where the destination is set to

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 to unzip files

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
}
like image 39
Faizaan Khan Avatar answered Nov 12 '22 12:11

Faizaan Khan