deg
deg

Reputation: 13

Unzip Multiple Files into Different Directories

I have multiple zip files.

They are called folder(1).zip, folder(2).zip, folder(3).zip. Using PowerShell, when I attempt to unzip them all into unique folders using this...

Get-ChildItem 'c:\users\name\downloads' -Filter *.zip | Expand-Archive -DestinationPath 'c:\users\name\downloads'  -Force

I get all of the files into one folder called "folder". How can I get the zip folders to unzip into separate folders?

Bonus question, is there a way, as part of this process, to rename each folder as it's coming out so folder(1).zip becomes Name-Here, folder(2).zip becomes Other-Name-Here, etc?

Thanks!

Upvotes: 1

Views: 2037

Answers (1)

marsze
marsze

Reputation: 17055

Because you specify only one destination path they will all be extracted into c:\users\name\downloads. I suppose the zip archives each contain a folder named "folder", so all contents from all archives end up together in c:\users\name\downloads\folder

You would have to specify a different destination path for each archive. Not sure what your naming convention should be, I have used a simple counter:

$counter = 0
Get-ChildItem 'c:\users\name\downloads' -Filter *.zip | foreach {
    $destination = Join-Path $_.DirectoryName ("YourName" + $counter++)
    Expand-Archive $_.FullName -DestinationPath $destination
}

Of course I suppose, now every of those folders will have the subfolder "folder", but if that's how the archives are built there's not really a way to change that. If you are absolutely sure that all archives have that subfolder, you could do something like this:

$counter = 0
Get-ChildItem 'c:\users\name\downloads' -Filter *.zip | foreach {
    # expand to the root folder first
    Expand-Archive $_.FullName -DestinationPath $_.DirectoryName
    # now rename the extracted "folder" to whatever you like
    Rename-Item (Join-Path $_.DirectoryName "folder") -NewName ("YourName" + $counter++)
}

Upvotes: 1

Related Questions