Home > OS >  PowerShell: extract multiple archives - script error
PowerShell: extract multiple archives - script error

Time:11-20

I have a folder which contains multiple zip archives. I need to extract all of them into subfolders named the same way initial files are (but without ".zip") To do so I created the following script:

$archives = Get-ChildItem . -Filter *.zip
foreach($zip in $archives)
{
Expand-Archive $zip.FullName -DestinationPath "{$zip.BaseName}"
}

If I run it the first file in the current folder is unpacked properly but for each subsequent file the folder is created but then there is an error "Expand-Archive : The path '' either does not exist or is not a valid file system path." And the folder is empty, nothing is unpacked. I inspect $zip object in a debugger on each iteration, it seems correct.

Any idea why it happens?

Thanks!

CodePudding user response:

Try with:

$archives = Get-ChildItem C:\temp -Filter *.zip
foreach($zip in $archives)
{
    Expand-Archive $zip.FullName -DestinationPath "$($zip.DirectoryName)\$($zip.BaseName)"
}

UPDATE

When testing names that include wildcard like '[' or we have to escape them in PowerShell

Example, testing if folder test[3] exists without and with escaping characters


C:\> Test-Path C:\temp\test[3]
False

C:\> Test-Path 'C:\temp\test`[2`]'
True

As wildcard characters are not supported, we need to modify script to handle names like test[2].zip

updated code will look like:

$archives = Get-ChildItem C:\temp -Filter *.zip
foreach($zip in $archives)
{
    $destination = "$($zip.DirectoryName)\$($zip.BaseName)"
    $destinationWithEscapedName = [WildcardPattern]::Escape($destination)

    $zipName = [WildcardPattern]::Escape($zip.FullName)

    Expand-Archive $zipName -DestinationPath $destination
}
  • Related