Trying to extract just .sql files from zip powershell

前端 未结 2 1809
暖寄归人
暖寄归人 2021-01-17 01:37

I am trying to search thru a zip file and just extract all of the .sql files to a directory. I can make it extract all the files, but there are over 200 misc files in the z

相关标签:
2条回答
  • 2021-01-17 02:14

    If you have (or grab) the PowerShell Community Extensions, you can use its archive commands:

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

    If you are on PowerShell V3 on a system with .NET 4.5 installed, you can use the System.IO.Compression.ZipFile class to extract the sql files.

    Add-Type -Assembly system.io.compression.filesystem
    [IO.Compression.ZipFile]::ExtractToDirectory($zipPath, $extractPath)
    
    0 讨论(0)
  • 2021-01-17 02:16

    I'd simplify it a little and use variables instead of the string literals, like this:

    $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($_)
    }
    

    but other than that your code should do just fine.

    Note, however, that it won't recurse into nested folders inside the zip file. You need something like this for processing nested folders as well:

    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
    
    0 讨论(0)
提交回复
热议问题