Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell 2.0 generates nulls between characters

With powershell 2.0:

write-output "abcd" >> mytext.txt  

returns:

a nul b nul c nul d nul

od -c shows the nul as a true binary zero, \0 , or: a \0 b \0 c \0 d \0 (and \r \0 \n \0).

I am trying to generate some SQL, so I don't think this will do. Any ideas of what's going on and how to use write-output to just get the specified characters?

like image 560
cvsdave Avatar asked Sep 27 '10 17:09

cvsdave


People also ask

How do you handle NULL in PowerShell?

$null is an automatic variable in PowerShell used to represent NULL. You can assign it to variables, use it in comparisons and use it as a place holder for NULL in a collection. PowerShell treats $null as an object with a value of NULL. This is different than what you may expect if you come from another language.

How do I return a NULL in PowerShell?

You can use $null to check an undefined variable. If the variable is not initialized with a value, it is undefined. This command checks if $Author is null in PowerShell. It returns the TRUE value as it is not initialized.

What does out NULL mean in PowerShell?

The Out-Null cmdlet sends its output to NULL, in effect, removing it from the pipeline and preventing the output to be displayed at the screen.

How do I check if something is NULL in PowerShell?

$null is one of the automatic variables in PowerShell, which represents NULL. You can use the -eq parameter to check if a string variable equals $null . It returns True if the variable is equal to $null and False if the variable is not equal to $null .


1 Answers

This is because write-output defaults to UTF-16 text encoding, which is 2 bytes per character. When you are dealing with text that fits into the ASCII codepage range, the 2nd byte of each character will be zero.

This is controlled by the $OutputEncoding global variable, so you could set that to ASCII.

Another option is to use the cmdlet Out-File, which has an explicit encoding parameter. I would suggest you use this instead of output redirection, because that saves you from changing your environment globally (by setting the global preference variable $OutputEncoding)

Using Out-File, and setting encoding to be ASCII, your example would look like this:

"abcd" | out-file "mytext.txt" -Encoding ASCII

Do be aware that not all characters are representable in ASCII, and you should determine whether this is an appropiate encoding for your purpose. Personally I would typically go for UTF-8, since it is ASCII equivalent when characters fall in the ASCII range from 0-127, but also handles international characters. Obligatory link about text encoding.

like image 127
driis Avatar answered Sep 18 '22 17:09

driis