繁体   English   中英

尝试从zip powershell中仅提取.sql文件

[英]Trying to extract just .sql files from zip powershell

我正在尝试通过一个zip文件进行搜索,然后将所有.sql文件提取到一个目录中。 我可以提取所有文件,但是zip中有200多个misc文件,我只需要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 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)

我将其简化一些,并使用变量代替字符串文字,如下所示:

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM