archive-utils.ps1
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# archive-utils.ps1 — archive utilities =======================================

# Extract an archive into a destination directory.
#
# Uses Windows tar.exe (ships with Win10 1803+) for all common formats.
#
# Supported formats:
#   .zip, .tar, .tar.gz / .tgz, .tar.bz2, .tar.xz, .tar.zst
#
# Flags:
#   -Cleanup   fix redundant foo/foo/ nesting inside the extracted folder
#   -Flat      extract directly into dest, no subfolder created
#
# Examples:
#   extract archive.tar.gz
#   extract release.zip . -Cleanup
#   extract tools.tar.xz C:\tools -Flat
function Invoke-Extract {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Archive,

        [Parameter(Position = 1)]
        [string]$Dest = ".",

        [switch]$Cleanup,
        [switch]$Flat,

        [Alias('h')]
        [switch]$Help
    )

    if ($Help) { $MyInvocation.MyCommand | Get-Help; return }

    # Verify tar is available
    $TarExe = "$env:SystemRoot\System32\tar.exe"
    if (-not (Test-Path $TarExe)) {
        Write-Error "extract: tar.exe not found at '$TarExe'. Windows 10 1803+ required."
        return
    }

    # Resolve paths
    $File = (Resolve-Path $Archive -ErrorAction Stop).Path
    $Out = (Resolve-Path $Dest    -ErrorAction Stop).Path

    # Detect format
    $Lower = $File.ToLower()
    $Supported = @('.zip', '.tar', '.tar.gz', '.tgz', '.tar.bz2', '.tar.xz', '.tar.zst')
    $Matched = $Supported | Where-Object { $Lower.EndsWith($_) }

    if (-not $Matched) {
        $Ext = [System.IO.Path]::GetExtension($File)
        Write-Error "extract: unsupported format '$Ext'. Supported: $($Supported -join ', ')"
        return
    }

    # Derive stem for output folder
    $BaseName = [System.IO.Path]::GetFileName($File)
    $Compounds = @('.tar.gz', '.tar.bz2', '.tar.xz', '.tar.zst', '.tgz')
    $Stem = $BaseName

    foreach ($C in $Compounds) {
        if ($BaseName.ToLower().EndsWith($C)) {
            $Stem = $BaseName.Substring(0, $BaseName.Length - $C.Length)
            break
        }
    }
    if ($Stem -eq $BaseName) {
        $Stem = [System.IO.Path]::GetFileNameWithoutExtension($BaseName)
    }

    # Prepare target directory
    $Target = if ($Flat) { $Out } else { Join-Path $Out $Stem }
    if (-not $Flat) { New-Item -ItemType Directory -Path $Target -Force | Out-Null }

    # Extract
    & $TarExe -xf $File -C $Target 2>&1 | ForEach-Object {
        if ($_ -match 'error|failed|cannot') { Write-Warning $_ }
    }

    # Cleanup nested foo/foo/
    if ($Cleanup -and -not $Flat) {
        $Inner = Join-Path $Target $Stem
        if ((Test-Path $Inner) -and (Get-Item $Inner).PSIsContainer) {
            $Children = Get-ChildItem -LiteralPath $Inner
            if ($Children) {
                foreach ($Child in $Children) {
                    $DestPath = Join-Path $Target $Child.Name
                    if (Test-Path $DestPath) { Remove-Item $DestPath -Recurse -Force }
                    Move-Item $Child.FullName $DestPath
                }
            }
            Remove-Item $Inner -Force
        }
    }

    Write-Host "Extracted to: " -NoNewline -ForegroundColor Blue
    Write-Host $Target
}

Set-Alias -Name extract -Value Invoke-Extract -Scope Global

# Compress a file or folder into an archive.
#
# Uses Windows tar.exe (ships with Win10 1803+).
# Format is inferred from the output filename extension.
#
# Supported formats:
#   .zip, .tar, .tar.gz / .tgz, .tar.bz2, .tar.xz, .tar.zst
#
# Examples:
#   compress my-folder output.tar.gz
#   compress my-folder output.zip
#   compress file.txt backup.tar.xz
function Invoke-Compress {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Path,

        [Parameter(Mandatory, Position = 1)]
        [string]$Output,

        [Alias('h')]
        [switch]$Help
    )

    if ($Help) { $MyInvocation.MyCommand | Get-Help; return }

    # Verify tar is available
    $TarExe = "$env:SystemRoot\System32\tar.exe"
    if (-not (Test-Path $TarExe)) {
        Write-Error "compress: tar.exe not found at '$TarExe'. Windows 10 1803+ required."
        return
    }

    # Resolve source path
    $Source = (Resolve-Path $Path -ErrorAction Stop).Path

    # Detect format from output extension
    $Lower = $Output.ToLower()
    $Supported = @('.zip', '.tar', '.tar.gz', '.tgz', '.tar.bz2', '.tar.xz', '.tar.zst')
    $Matched = $Supported | Where-Object { $Lower.EndsWith($_) }

    if (-not $Matched) {
        $Ext = [System.IO.Path]::GetExtension($Output)
        Write-Error "compress: unsupported format '$Ext'. Supported: $($Supported -join ', ')"
        return
    }

    # Resolve output to absolute path
    $OutFile = $Output
    if (-not [System.IO.Path]::IsPathRooted($OutFile)) {
        $OutFile = Join-Path (Get-Location).Path $OutFile
    }

    # Compress
    & $TarExe -cf $OutFile -C (Split-Path $Source -Parent) (Split-Path $Source -Leaf) 2>&1 | ForEach-Object {
        if ($_ -match 'error|failed|cannot') { Write-Warning $_ }
    }

    Write-Host "Compressed to: " -NoNewline -ForegroundColor Blue
    Write-Host $OutFile
}

Set-Alias -Name compress -Value Invoke-Compress -Scope Global