Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe the output of a command to a file without powershell changing the encoding?

I want to pipe the output of a command to a file:

PS C:\Temp> create-png > binary.png

I noticed that Powershell changes the encoding and that I can manually give an encoding:

PS C:\Temp> create-png | Out-File "binary.png" -Encoding OEM

However there is no RAW encoding option, even the OEM option changes newline bytes (0xA resp 0xD) to the windows newline byte sequence (0xD 0xA) thereby ruining any binary format.

How can I prevent Powershell from changing the encoding when piping to a file?

Related questions

  • PowerShellscript, bad file encoding conversation
  • Write output to a text file in PowerShell
  • Using PowerShell to write a file in UTF-8 without the BOM
like image 820
Micha Wiedenmann Avatar asked Mar 17 '23 06:03

Micha Wiedenmann


1 Answers

Try using set-content:

create-png | set-content -path myfile.png -encoding byte

If you need additional info on set-content just run

get-help set-content

You can also use 'sc' as a shortcut for set-content.

Tested with the following, produces a readable PNG:

function create-png()
{
    [System.Drawing.Bitmap] $bitmap = new-object 'System.Drawing.Bitmap'([Int32]32,[Int32]32);
    $graphics = [System.Drawing.Graphics]::FromImage($bitmap);
    $graphics.DrawString("TEST",[System.Drawing.SystemFonts]::DefaultFont,[System.Drawing.SystemBrushes]::ActiveCaption,0,0);
    $converter = new-object 'System.Drawing.ImageConverter';
    return([byte[]]($converter.ConvertTo($bitmap, [byte[]])));
}

create-png | set-content -Path 'fromsc.png' -Encoding Byte

If you are calling out to a non-PowerShell executable like ipconfig and you just want to capture the bytes from Standard Output, try Start-Process:

Start-Process -NoNewWindow -FilePath 'ipconfig' -RedirectStandardOutput 'output.dat'
like image 64
RickH Avatar answered Apr 23 '23 18:04

RickH