Skip to content

Instantly share code, notes, and snippets.

@rjmholt
Created February 21, 2019 07:36
Show Gist options
  • Save rjmholt/3d8dd4849f718c914132ce3c5b278e0e to your computer and use it in GitHub Desktop.
Save rjmholt/3d8dd4849f718c914132ce3c5b278e0e to your computer and use it in GitHub Desktop.
PowerShell BOM-less encoding
$badBytes = [byte[]]@(0xC3, 0x80)
$utf8Str = [System.Text.Encoding]::UTF8.GetString($badBytes)
$bytes = [System.Text.Encoding]::ASCII.GetBytes('Write-Output "') + [byte[]]@(0xC3, 0x80) + [byte[]]@(0x22)
$path = Join-Path ([System.IO.Path]::GetTempPath()) 'encodingtest.ps1'
try
{
[System.IO.File]::WriteAllBytes($path, $bytes)
switch (& $path)
{
$utf8Str
{
return 'UTF-8'
break
}
default
{
return 'Windows-1252'
break
}
}
}
finally
{
Remove-Item $path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment