【问题标题】:Trying to extract just .sql files from zip powershell试图从 zip powershell 中仅提取 .sql 文件
【发布时间】:2014-01-14 02:23:35
【问题描述】:

我正在尝试通过一个 zip 文件进行搜索,然后将所有 .sql 文件提取到一个目录中。我可以让它提取所有文件,但是 zip 中有超过 200 个杂项文件,我只需要 6 个 .sql 文件。有没有简单的方法来指定 .sql?

这是我试图开始工作的示例代码,如果有更好的方法,我很乐意听到。

$shell = new-object -com shell.application
$zip = $shell.NameSpace(“C:\Temp”)

foreach($item in $zip.items()){

    if([System.IO.Path]::GetExtension($item.Path) -eq ".sql"){

        $shell.Namespace(“C:\Project\”).copyhere($item)

    }

}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    如果你有(或抓住)PowerShell Community Extensions,你可以使用它的归档命令:

    Read-Archive C:\temp\foo.zip | %{$_} | Where Name -match '\.sql' | Expand-Archive
    

    如果您在安装了 .NET 4.5 的系统上使用 PowerShell V3,则可以使用 System.IO.Compression.ZipFile 类来提取 sql 文件。

    Add-Type -Assembly system.io.compression.filesystem
    [IO.Compression.ZipFile]::ExtractToDirectory($zipPath, $extractPath)
    

    【讨论】:

      【解决方案2】:

      我会稍微简化一下并使用变量而不是字符串文字,如下所示:

      $shell = New-Object -COM 'Shell.Application'
      
      $zipfile     = 'C:\Temp\some.zip'
      $destination = 'C:\Project'
      
      $zip = $shell.NameSpace($zipfile)
      
      $zip.Items() | ? { $_.Path -like '*.sql' } | % {
        $shell.NameSpace($destination).CopyHere($_)
      }
      

      但除此之外,您的代码应该可以正常工作。

      但请注意,它不会递归到 zip 文件内的嵌套文件夹中。您也需要这样的东西来处理嵌套文件夹:

      function ExtractZip($fldr, $dst) {
        $fldr.Items() | ? { $_.Path -like '*.sql' } | % {
          $shell.NameSpace($dst).CopyHere($_)
        }
        $fldr.Items() | ? { $_.Type -eq 'File folder' } | % {
          ExtractZip $_.GetFolder $dst
        }
      }
      
      ExtractZip $shell.NameSpace($zipfile) $destination
      

      【讨论】:

        猜你喜欢
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        • 2017-09-02
        • 1970-01-01
        • 1970-01-01
        • 2014-10-13
        • 1970-01-01
        • 2023-03-21
        相关资源
        最近更新 更多