2014-01-13 74 views
0

我想通过压缩文件进行搜索,并将所有.sql文件解压缩到目录中。我可以提取所有文件,但zip中有超过200个misc文件,而我只需要6个.sql文件。有没有简单的方法来指定.sql?试图从zip压缩包中提取刚才的.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) 

    } 

} 

回答

3

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

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

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

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

我把它简化一点,使用变量,而不是字符串文字,就像这样:

$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