【问题标题】:PowerShell: Extract specific files/folders from a zipped archivePowerShell:从压缩档案中提取特定文件/文件夹
【发布时间】:2017-09-28 16:22:28
【问题描述】:

foo.zip 包含:

a
b
c
|- c1.exe 
|- c2.dll 
|- c3.dll

a, b, c 是文件夹。

如果我

Expand-Archive .\foo.zip -DestinationPath foo 

foo.zip 中的所有文件/文件夹都已提取。
我只想提取c 文件夹。

【问题讨论】:

    标签: powershell zip archive unzip


    【解决方案1】:

    试试这个

    Add-Type -Assembly System.IO.Compression.FileSystem
    
    #extract list entries for dir myzipdir/c/ into myzipdir.zip
    $zip = [IO.Compression.ZipFile]::OpenRead("c:\temp\myzipdir.zip")
    $entries=$zip.Entries | where {$_.FullName -like 'myzipdir/c/*' -and $_.FullName -ne 'myzipdir/c/'} 
    
    #create dir for result of extraction
    New-Item -ItemType Directory -Path "c:\temp\c" -Force
    
    #extraction
    $entries | foreach {[IO.Compression.ZipFileExtensions]::ExtractToFile( $_, "c:\temp\c\" + $_.Name) }
    
    #free object
    $zip.Dispose()
    

    【讨论】:

    • 这就像一个魅力,应该被接受。 System.IO 不是“外部库”。这是.NET
    • 您可以使用以下正则表达式过滤条目:$zip.Entries | Where-Object { $_ -match 'myzipdir/c/+.' }
    【解决方案2】:

    这个不使用外部库:

    $shell= New-Object -Com Shell.Application 
    $shell.NameSpace("$(resolve-path foo.zip)").Items() | where Name -eq "c" | ? {
        $shell.NameSpace("$PWD").copyhere($_) } 
    

    也许可以简化一点。

    【讨论】:

    • 它对我不起作用。它总是返回空结果。如何只显示 zip 文件的内容? $i = $shell.Namespace("$(resolve-path .\myarc.zip)") 然后 $i 给我一个不可枚举的对象;我知道路径是正确的,因为当它不正确时,它会返回 null。
    【解决方案3】:

    这里有一些对我有用的东西。当然,您需要编辑代码以符合您的目标

    $results =@()
    
    foreach ($p in $Path)
    {
    
    
    $shell = new-object -Comobject shell.application
    $fileName = $p
    $zip = $shell.namespace("$filename")
    
    $Results +=  $zip.items()| where-object { $_.Name -like "*C*" -or  $_.Name -like 
    "*b*"  }
    }
    foreach($item in $Results )
    {
    
    $shell.namespace($dest).copyhere($item)
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-09
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多