I want to extract all .zip files in a given directory in temp using powershell
Asked Answered
B

3

16

I wrote the following code for extracting the .zip files to temp:

function Expand-ZIPFile($file, $destination)
{
    $shell = new-object -com shell.application
    $zip = $shell.NameSpace($file)
    foreach ($item in $zip.items()) {
       $shell.Namespace($destination).copyhere($item)
    }
}

Expand-ZIPFile -file "*.zip" -destination "C:\temp\CAP"

But I got the following error:

PS C:\Users\v-kamoti\Desktop\CAP> function Expand-ZIPFile($file, $destination)
{
   $shell = new-object -com shell.application
   $zip = $shell.NameSpace($file)
   foreach ($item in $zip.items()) {
      $shell.Namespace($destination).copyhere($item)
   }
}

Expand-ZIPFile -file "*.zip" -destination "C:\temp\CAP"
You cannot call a method on a null-valued expression.
At line:5 char:19
+  foreach($item in $zip.items())
+                   ~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
Brose answered 11/2, 2015 at 6:50 Comment(0)
B
34
Get-ChildItem 'path to folder' -Filter *.zip | Expand-Archive -DestinationPath 'path to extract' -Force

requires ps v5

Bivens answered 6/3, 2017 at 3:31 Comment(1)
fyi still useful in 2020 for pushing data into Snowflake cloud. This is used as intrim step to get data from sftp site, extra the '.zip' files (as its a format not supported by Snowflake currently). And then pushing the raw .csv files to blob.Susann
C
7

You can use this if you want to create a new folder for each zip file:

#input variables
$zipInputFolder = 'C:\Users\Temp\Desktop\Temp'
$zipOutPutFolder = 'C:\Users\Temp\Desktop\Temp\Unpack'

#start
$zipFiles = Get-ChildItem $zipInputFolder -Filter *.zip

foreach ($zipFile in $zipFiles) {

    $zipOutPutFolderExtended = $zipOutPutFolder + "\" + $zipFile.BaseName
    Expand-Archive -Path $zipFile.FullName -DestinationPath $zipOutPutFolderExtended

    }
Coburg answered 3/5, 2019 at 9:31 Comment(0)
B
1

You have to provide the full path explicitly (without wildcards) in the following call:

$shell.NameSpace($file)

You could rewrite your function like this:

function Expand-ZIPFile($file, $destination)
{
    $files = (Get-ChildItem $file).FullName

    $shell = new-object -com shell.application

    $files | %{
        $zip = $shell.NameSpace($_)

        foreach ($item in $zip.items()) {
           $shell.Namespace($destination).copyhere($item)
        }
    }
}
Bedaub answered 11/2, 2015 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.