我想使用 powershell 提取临时目录中给定目录中的所有 .zip 文件

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

我编写了以下代码来将 .zip 文件提取到临时文件:

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"

但是我得到了以下错误:

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

您必须在以下调用中明确提供完整路径(不带通配符):

$shell.NameSpace($file)

您可以这样重写您的函数:

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)
        }
    }
}
Get-ChildItem 'path to folder' -Filter *.zip | Expand-Archive -DestinationPath 'path to extract' -Force

需要 ps v5

如果要为每个 zip 文件创建一个新文件夹,可以使用此方法:

#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

    }

Get-ChildItem 'Source Folder path' -过滤器 *.zip | Expand-Archive -DestinationPath 'Destination Folder path' -Force