-
-
Save phuysmans/c9e47603c45b4dfe098fdf58b53b713b to your computer and use it in GitHub Desktop.
PowerShell encoding Zip paths to use forward slash (Zip Spec) instead of backslash (Windows Style); for portable zip files - thanks to @sethjackson
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# When using System.IO.Compression.ZipFile.CreateFromDirectory in PowerShell, it still uses backslashes in the zip paths | |
# despite this https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-ziparchiveentry-fullname-path-separator | |
# Based upon post by Seth Jackson https://sethjackson.github.io/2016/12/17/path-separators/ | |
# | |
# PowerShell 5 (WMF5) & 6 | |
# Using class Keyword https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Classes | |
# | |
Add-Type -AssemblyName System.Text.Encoding | |
Add-Type -AssemblyName System.IO.Compression.FileSystem | |
class FixedEncoder : System.Text.UTF8Encoding { | |
FixedEncoder() : base($true) { } | |
[byte[]] GetBytes([string] $s) | |
{ | |
$s = $s.Replace("\\", "/"); | |
return ([System.Text.UTF8Encoding]$this).GetBytes($s); | |
} | |
} | |
[System.IO.Compression.ZipFile]::CreateFromDirectory($dirToZip, $zipFilePath, [System.IO.Compression.CompressionLevel]::Optimal, $false, [FixedEncoder]::new()) | |
# | |
# PowerShell 4 (WMF4) | |
# Using Add-Type cmdlet https://msdn.microsoft.com/en-us/powershell/reference/4.0/microsoft.powershell.utility/add-type | |
# | |
Add-Type -AssemblyName System.Text.Encoding | |
Add-Type -AssemblyName System.IO.Compression.FileSystem | |
$EncoderClass=@" | |
public class FixedEncoder : System.Text.UTF8Encoding { | |
public FixedEncoder() : base(true) { } | |
public override byte[] GetBytes(string s) { | |
s = s.Replace("\\", "/"); | |
return base.GetBytes(s); | |
} | |
} | |
"@ | |
Add-Type -TypeDefinition $EncoderClass | |
$Encoder = New-Object FixedEncoder | |
[System.IO.Compression.ZipFile]::CreateFromDirectory($dirToZip, $zipFilePath, [System.IO.Compression.CompressionLevel]::Optimal, $false, $Encoder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment