Search code examples
powershellunzip7zip

Unzip archive zip file into folder with same name as archive zip file


I am able to successfully unzip a zipped file using a Powershell script as follows:

$filePath = "s:\Download Data Feed\"
$zip = Get-ChildItem -Recurse -Path $filePath | Where-Object { $_.Extension -eq ".zip" } 

foreach ($file in $zip) { 
Expand-7Zip -ArchiveFileName $file -Password "Password" -TargetPath $filePath
}

Read-Host -Prompt "Press Enter to exit"

The zip file are csv files. But what I would like is to unzip the csv file in a folder of the same name as the zip file itself (just as when you right click the zipped file you can choose to extract it as the file itself or to a folder of the same name as the zip file). I've tried looking at the switches for Expand-7Zip command but can't find any.

Thanks


Solution

  • You could do something like the following (I cannot test with Expand-7Zip):

    $filePath = "s:\Download Data Feed\"
    $zip = Get-ChildItem -File -Recurse -Path $filePath | Where-Object { $_.Extension -eq ".zip" }
    
    foreach ($file in $zip) { 
        $target = Join-Path $filePath $file.BaseName
        if (!(Test-Path $target -PathType Container)) {
            $null = New-Item -ItemType Directory -Path $target
        }
        Expand-7Zip -ArchiveFileName $file -Password "Password" -TargetPath $target
    }
    

    Explanation:

    Each FileInfo object contained in the $zip collection has a property, BaseName, which is the name of the file without the extension.

    Join-Path is used to join a path with a child path. The child path here will be the BaseName value of $file during each iteration.

    Test-Path is used to verify if a path already exists. If the $target path does not exist, it will be created due to the New-Item command.


    Another approach to getting the target folder path is to simply use a regex replace, which is likely more efficient:

    $target = $file.FullName -replace '\.zip$'