Home > front end >  PowerShell extract each zip file to own folder
PowerShell extract each zip file to own folder

Time:10-21

I would like to unzip some files each into their own folder with the same name as the zip file. I have been doing clunky things like this, but as this is PowerShell, there is usually a much smarter way to achieve things.

Are there some kind of one-or-two-liner ways that I can operate on each zip file in a folder and extract it into a subfolder of the same name as the zip (but without the extension)?

foreach ($i in $zipfiles) { 
    $src = $i.FullName
    $name = $i.Name
    $ext = $i.Extension
    $name_noext = ($name -split $ext)[0]
    $out = Split-Path $src
    $dst = Join-Path $out $name_noext
    $info  = "`n`n$name`n==========`n"
    if (!(Test-Path $dst)) {
        New-Item -Type Directory $dst -EA Silent | Out-Null
        Expand-Archive -LiteralPath $src -DestinationPath $dst -EA Silent | Out-Null
    }
}

CodePudding user response:

You could do with a few less variables. When the $zipfiles collection contains FileInfo objects as it appears, most variables can be replaced by using the properties the objects already have.

Also, try to avoid concatenating to a variable with = because that is both time and memory consuming.
Just capture the result of whatever you output in the loop in a variable.

Something like this:

# capture the stuff you want here as array
$info = foreach ($zip in $zipfiles) { 
    # output whatever you need to be collected in $info
    $zip.Name
    # construct the folderpath for the unzipped files
    $dst = Join-Path -Path $zip.DirectoryName -ChildPath $zip.BaseName
    if (!(Test-Path $dst -PathType Container)) {
        $null = New-Item -ItemType Directory $dst -ErrorAction SilentlyContinue
        $null = Expand-Archive -LiteralPath $zip.FullName -DestinationPath $dst -ErrorAction SilentlyContinue
    }
}

# now you can create a multiline string from the $info array
$result = $info -join "`r`n==========`r`n"
  • Related