使用PowerShell解压GZip正常,能否直接从.tar.gz提取文件?
PowerShell 处理 tar.gz 及 tar 格式文件方案
单独打开.tar格式文件方法
如果已经生成了.tar后缀的文件,可直接用PowerShell内置命令提取内容,无需安装第三方工具:
Expand-Archive -Path "C:\temp\maxmind\temp.tar" -DestinationPath "C:\temp\maxmind\extract\"
其中-Path参数填写.tar文件的本地路径,-DestinationPath填写提取后文件的存放目录,目录不存在时会自动创建。
直接解压tar.gz无需生成中间.tar文件方案
方案1:内置命令(推荐,适用于PowerShell 5.1及以上版本)
Windows 10 1709版本之后系统默认自带的PowerShell版本已原生支持tar.gz格式解压,一行命令即可完成操作,全程不会生成中间.tar文件:
Expand-Archive -Path "C:\temp\maxmind\temp.tar.gz" -DestinationPath "C:\temp\maxmind\extract\"
方案2:自定义流处理函数(兼容旧版本运行环境)
如果运行环境PowerShell版本较低,不支持内置的Expand-Archive命令,可直接调用.NET类在内存中完成gzip解压和tar内容解析,无需写入中间.tar文件到本地磁盘:
Function Extract-TarGz { Param( $infile, $destinationPath ) # 自动创建目标存放目录 if (-not (Test-Path $destinationPath)) { New-Item -ItemType Directory -Path $destinationPath | Out-Null } $fileStream = New-Object System.IO.FileStream $infile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read) $gzipStream = New-Object System.IO.Compression.GzipStream $fileStream, ([IO.Compression.CompressionMode]::Decompress) $tarReader = New-Object System.Formats.Tar.TarReader $gzipStream, $false while ($entry = $tarReader.GetNextEntry()) { # 跳过目录条目,仅处理文件 if ($entry.EntryType -ne [System.Formats.Tar.TarEntryType]::RegularFile) { continue } $outputPath = Join-Path $destinationPath $entry.Name $entryDir = Split-Path $outputPath -Parent # 自动创建文件对应的子目录 if (-not (Test-Path $entryDir)) { New-Item -ItemType Directory -Path $entryDir | Out-Null } $entryStream = $entry.Open() $outputStream = New-Object System.IO.FileStream $outputPath, ([IO.FileMode]::Create), ([IO.FileAccess]::Write) $entryStream.CopyTo($outputStream) $outputStream.Close() $entryStream.Close() } $tarReader.Dispose() $gzipStream.Close() $fileStream.Close() } # 调用示例 Extract-TarGz -infile "C:\temp\maxmind\temp.tar.gz" -destinationPath "C:\temp\maxmind\extract\"
如果运行时提示找不到System.Formats.Tar类型,将.NET运行时升级到3.0及以上,或是将PowerShell升级到7+版本即可正常使用。
内容的提问来源于stack exchange,提问作者Francesco Mantovani
相关产品推荐
相关产品推荐

