Thứ Hai, 13 tháng 11, 2023

Why does powershell appending to a file insert whitespace (NUL)

 I am running this command

Get-Content generated\no_animate.css >> generated\all.css

I want to append the contents of no_animate.css to all.css.

This is working if I run it like this from a cmd prompt:

powershell Get-Content generated\no_animate.css >> generated\all.css

If I put the exact same code into a .ps1 file and run that it is copying the contents but inserting whitespace (Represented as NUL in texteditor) between every character.

Why would it be doing this? How do I prevent it?


=============

In PowerShell the redirection operators > and >> are shorthands for Out-File and Out-File -Append respectively. Out-File uses Unicode (little endian UTF-16 specifically) as its default encoding. With this encoding every character is represented by 2 bytes instead of just 1. For ASCII characters (characters from the basic latin block) the first byte has the value 0.

Running powershell Get-Content generated\no_animate.css >> generated\all.css from CMD uses the CMD redirection operator instead of the PowerShell one, which doesn't transform the text to Unicode.

If you want to use PowerShell and your input file is ascii-encoded use Add-Content (available in PowerShell v3 or newer):

Get-Content generated\no_animate.css | Add-Content generated\all.css

or Out-File with explicit encoding.

Get-Content generated\no_animate.css |
    Out-File generated\all.css -Append -Encoding Ascii

Share This!


Không có nhận xét nào:

Đăng nhận xét