Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unzip multiple files?

I am attempting to loop through zip files in a folder and extract them. I am receiving a null error for the zip.items(). How could this value be null?

When I Write-Host $zip the value that is posted is System.__ComObject.

$dira = "D:\User1\Desktop\ZipTest\IN"
$dirb = "D:\User1\Desktop\ZipTest\DONE\" 

$list = Get-childitem -recurse $dira -include *.zip

$shell = new-object -com shell.application

foreach($file in $list)
{
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($dirb).copyhere($file)
    }
    Remove-Item $file
}

The error message I am receiving is:

You cannot call a method on a null-valued expression.  
At D:\Users\lr24\Desktop\powershellunziptest2.ps1:12 char:29  
+     foreach($item in $zip.items <<<< ())
    + CategoryInfo          : InvalidOperation: (items:String) [], RuntimeException  
    + FullyQualifiedErrorId : InvokeMethodOnNull
like image 603
cchristie45 Avatar asked Feb 26 '26 12:02

cchristie45


2 Answers

$file is a FileInfo object, but the NameSpace() method expects either a string with a full path or a numeric constant. Also, you need to copy $item, not $file.

Change this:

foreach($file in $list)
{
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($dirb).copyhere($file)
    }
    Remove-Item $file
}

into this:

foreach($file in $list)
{
    $zip = $shell.NameSpace($file.FullName)
    foreach($item in $zip.items())
    {
        $shell.Namespace($dirb).copyhere($item)
    }
    Remove-Item $file
}
like image 167
Ansgar Wiechers Avatar answered Feb 28 '26 23:02

Ansgar Wiechers


If you have 7-zip in your $env:path

PS> $zips = dir *.zip
PS> $zips | %{7z x $_.FullName}

#unzip with Divider printed between unzip commands
PS> $zips | %{echo "`n`n======" $_.FullName; 7z x $_.FullName}

you can get 7-zip here:

http://www.7-zip.org/

PS> $env:path += ";C:\\Program Files\\7-Zip"

Explanation:

Percent followed by curly braces is called the foreach operator: %{ } This operator means that "Foreach" object in the pipe, the code in the curly braces is called with the object placed in the "$_" variable.

like image 38
Bimo Avatar answered Mar 01 '26 01:03

Bimo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!