serob
serob

Reputation: 5

unzip zip files into multiple folders with powershell

I have 5 zip files and 5 folders respectively. Files are: FranceData.zip, USAdata.zip, GermanData.zip, Italydata.zip and DanemarkData.zip. Folders are: FranceFolder, USAFolder, GermanFolder, ItalyFolder and DanemarkFolder. I would like to know how would I unzip these files into their respective folders using Array in Powershell. I am knew to Powershell and need help. Thank you

Upvotes: 0

Views: 1597

Answers (1)

Just-Harry
Just-Harry

Reputation: 72

This can be done using the Expand-Archive cmdlet, which is available in PowerShell 5 and above. (PowerShell's version can be checked via the $PSVersionTable variable.)

To extract a zip file to a specific folder the following syntax is used:

Expand-Archive -Path 'ZipFile.zip' -DestinationPath 'ZipFolder'

or

Expand-Archive -LiteralPath 'ZipFile.zip' -DestinationPath 'ZipFolder'

If the -Path parameter is used, PowerShell will recognise characters such as *, ?, [, ], as wildcards, which can cause unexpected behaviour for file-paths that contain square-brackets.
If the -LiteralPath parameter is used, PowerShell will not treat any characters as wildcard characters.


Assuming all your zip files and folders follow the same naming pattern you could use an array like so:

$Countries = @(
    'France',
    'USA',
    'German'
    'Italy',
    'Danemark'
)

foreach ($Country in $Countries)
{
    $ZipFilePath = $Country + 'Data.zip'
    $DestinationPath = $Country + 'Folder'

    Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}

If your files and folders don't follow the same naming pattern you could use a dictionary (or a collection of KeyValuePairs), like so:

$ZipFilesAndFolders = @{
    'FranceData.zip' = 'FranceFolder'
    'USAData.zip' = 'USAFolder'
    'GermanData.zip' = 'GermanFolder'
    'ItalyData.zip' = 'ItalyFolder'
    'DanemarkData.zip' = 'DanemarkFolder'
}

foreach ($KeyAndValue in $ZipFilesAndFolders.GetEnumerator())
{
    $ZipFilePath = $KeyAndValue.Key
    $DestinationPath = $KeyAndValue.Value

    Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}

With PowerShell 4 (and 3)

If you have .Net Framework 4.5 installed, you can use Microsoft.PowerShell.Archive which was created by the PowerShell team.
PowerShell 4 requires .Net Framework 4.5 so this should work without any system changes needed.
The module can be found at https://github.com/PowerShell/Microsoft.PowerShell.Archive

The syntax used is identical, the function is Expand-Archive and the parameters are -Path, -LiteralPath, and -DestinationPath.
Just ensure that you have imported the module before using it, this can be done using the Import-Module cmdlet like so:

Import-Module -Name 'Microsoft.PowerShell.Archive' -Force

PowerShell 2

A solution for PowerShell 2 can be found here: https://stackoverflow.com/a/37814462/9447234

Upvotes: 2

Related Questions