PowerShell – SharpCompress and untar

#needed to untar a tar.gz file and found the SharpCompress package, which will do it all!
#region InstallPackage SharpCompress if  (-NOT (Get-Package -Name 'SharpCompress' -ErrorAction SilentlyContinue)) { #need to install it if (Find-Package -Name 'SharpCompress' -ErrorAction SilentlyContinue) { Find-Package -Name SharpCompress  | Install-Package -Verbose } else { if (-NOT (Get-PackageSource -Name 'nuGet.org v2' -ErrorAction SilentlyContinue)) { Register-PackageSource -Name 'nuGet.org v2' -ProviderName NuGet -Location "https://www.nuget.org/api/v2/" } if (Find-Package -Name 'SharpCompress' -Source 'nuGet.org v2' -ErrorAction SilentlyContinue) { Find-Package -Name SharpCompress -Source 'nuGet.org v2' | Install-Package -Verbose } } } #endregion #region AddType SharpCompress $pkg=Get-Package -Name 'SharpCompress' $packageLocation = $pkg.Source $folder=$packageLocation.Substring(0,$packageLocation.LastIndexOf('\')) + '\lib\' $dll = Get-ChildItem -Path $folder -recurse -Include *.dll | Sort-Object -Descending | Select-Object -First 1 Add-Type -Path $dll.FullName #endregion
function Extract-CompressedFile { [Alias('UnTar')] [Alias('UnZip')] [Alias('UnRar')]
[CmdletBinding()] PARAM ([Parameter(Mandatory=$true, ValueFromPipeline=$true,Position=0)] [string]$sourcefile, [Parameter(Mandatory=$true,Position=1)] [string]$destinationDirectory)
if (-NOT (Test-Path -Path $sourcefile)) { Write-Error -Message ('{0} File Not Found.' -f $sourcefile) return } if (-NOT (Test-Path -Path $destinationDirectory -IsValid)) { Write-Error -Message ('{0} Is not a valid target path.' -f $destinationDirectory) return }
# use the generic ReaderFactory. It will open anything. # if it's a tar.gz, we'll go straight to the Tar file. $filestream=[System.IO.File]::OpenRead($Sourcefile)
$reader=[SharpCompress.Readers.ReaderFactory]::Open($filestream) While ($reader.MoveToNextEntry()) { Write-Verbose -Message $reader.Entry.Key if ($reader.Entry.IsDirectory) { $folder = $reader.Entry.Key $destDir = Join-path -Path $DestinationDirectory -ChildPath $folder if (-NOT (Test-Path -Path $destDir)) { $null=New-Item -Path $destDir -ItemType Directory -Force } } else { $file = $reader.Entry.Key $filepath = Join-Path -Path $DestinationDirectory -ChildPath $file if (Test-Path -Path $filepath) { Remove-Item -Path $filepath -Force -Verbose } $CreateNew = [System.IO.FileMode]::CreateNew $fs=[System.IO.File]::Open($filepath, $CreateNew) $reader.WriteEntryTo($fs) $fs.close() } }
$filestream.Close() }
$Source= "$HOME\Downloads\tar-latest.tar.gz" $Destination = 'C:\TEMP'
#Extract-CompressedFile -sourcefile $source -destinationDirectory $Destination UnTar "$HOME\Downloads\tar-latest.tar.gz" "C:\TEMP"
Comments (0)

Skip to main content