The problem was caused by:
Get-Content
without-raw
splits the file into an array of lines thus destroying the codeText.Encoding
interprets the binary code as text thus destroying the codeOut-File
is for text data, not binary code
The correct approach is to use IO.File ReadAllBytes:
$base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($FileName))
and WriteAllBytes to decode:
[IO.File]::WriteAllBytes($FileName, [Convert]::FromBase64String($base64string))