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

最后都变了- 提交于 2019-11-28 05:02:27

问题


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

回答1:


Get-ChildItem 'path to folder' -Filter *.zip | Expand-Archive -DestinationPath 'path to extract' -Force

requires ps v5




回答2:


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)
        }
    }
}



回答3:


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

    }


来源:https://stackoverflow.com/questions/28448202/i-want-to-extract-all-zip-files-in-a-given-directory-in-temp-using-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!