2015-02-05 2 views
2

Я ищу решение проблемы с созданием tar.gz-архива с помощью Powershell v4. Я не мог найти расширения/пакеты, созданные или проверенные Microsoft для обеспечения такой функциональности. Существуют ли такие решения [tar-ing и gzip-ing]?Как создать файл tar gz с помощью powershell

ответ

1

Microsoft внедрила gzipstream in System.IO.Compression в .Net 2.0 В C# есть множество примеров и многих других в powershell. Powershell Community Extensions также имеют функции Write-Zip и Write-Tar. Вот функция gzip, которую я сделал довольно давно. Он должен быть действительно обновлен для обработки нескольких входов и лучшего вывода. Он также обрабатывает только один файл за раз. Но вам нужно начать, если вы хотите увидеть, как это делается.

function New-GZipArchive 
{ 
    [CmdletBinding(SupportsShouldProcess=$true, 
        PositionalBinding=$true)] 
    [OutputType([Boolean])] 
    Param 
    (
     # The input file(s) 
     [Parameter(Mandatory=$true, 
        ValueFromPipeline=$true, 
        Position=0)] 
     [ValidateNotNull()] 
     [ValidateNotNullOrEmpty()] 
     [ValidateScript({Test-Path $_})] 
     [String] 
     $fileIn, 

     # The path to the requested output file 
     [Parameter(Position=1)] 
     [ValidateNotNull()] 
     [ValidateNotNullOrEmpty()] 
     #validation is done in the script as the only real way to determine if it is a valid path is to try it 
     [String] 
     $fileOut, 

     # Param3 help description 
     [Switch] 
     $Clobber 
    ) 
    Process 
    { 
     if ($pscmdlet.ShouldProcess("$fileIn", "Zip file to $fileOut")) 
     { 
      if($fileIn -eq $fileOut){ 
       Write-Error "You can't zip a file into itself" 
       return 
      } 
      if(Test-Path $fileOut){ 
       if($Clobber){ 
        Remove-Item $fileOut -Force -Verbose 
       }else{ 
        Write-Error "The output file already exists and the Clobber parameter was not specified. Please input a non-existent filename or specify the Clobber parameter" 
        return 
       } 
      } 
      try{ 
       #create read stream     
       $fsIn = New-Object System.IO.FileStream($fileIn, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read) 
       #create out stream 
       $fsOut = New-Object System.IO.FileStream($fileOut, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None) 
       #create gzip stream using out file stream 
       $gzStream = New-Object System.IO.Compression.GZipStream($fsout, [System.IO.Compression.CompressionMode]::Compress) 
       #create a shared buffer 
       $buffer = New-Object byte[](262144) #256KB 
       do{ 
        #read into buffer 
        $read = $fsIn.Read($buffer,0,262144) 
        #write buffer back out 
        $gzStream.Write($buffer,0,$read) 
       } 
       while($read -ne 0) 
      } 
      catch{ 
       #really should add better error handling 
       throw 
      } 
      finally{ 
       #cleanup 
       if($fsIn){ 
        $fsIn.Close() 
        $fsIn.Dispose() 
       } 
       if($gzStream){ 
        $gzStream.Close() 
        $gzStream.Dispose() 
       } 
       if($fsOut){ 
        $fsOut.Close() 
        $fsOut.Dispose() 
       } 
      } 
     } 
    } 
} 

Использование:

dir *.txt | %{New-GZipArchive $_.FullName $_.FullName.Replace('.txt','.gz') -verbose -clobber} 
VERBOSE: Performing operation "Zip file to C:\temp\a.gz" on Target "C:\temp\a.txt". 
VERBOSE: Performing operation "Remove file" on Target "C:\temp\a.gz". 
VERBOSE: Performing operation "Zip file to C:\temp\b.gz" on Target "C:\temp\b.txt". 
VERBOSE: Performing operation "Remove file" on Target "C:\temp\b.gz". 
VERBOSE: Performing operation "Zip file to C:\temp\c.gz" on Target "C:\temp\c.txt". 
VERBOSE: Performing operation "Remove file" on Target "C:\temp\c.gz". 
+1

насчет тарирования процесса? – user3376246

+1

Взгляните на расширения сообщества powershell https://pscx.codeplex.com/, у них есть скрипт write-tar. Я не знаю более простого способа сделать это, поскольку мне никогда не приходилось работать с файлами tar в Windows. – StephenP

+0

Расширения сообщества Powershell теперь находятся на Github: https://github.com/Pscx/Pscx – garie

Смежные вопросы