Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a difference between > operator and Set-Content cmdlet

Tags:

powershell

I figured out that these 2 lines:

echo "hello world" > hi.txt
echo "hello world" | Set-Content hi.txt

aren't doing exactly the same job. I created a simple script that replaces a content of some values in a configuration file and store it (using >), but that seems to store file in some weird format. Standard windows text editors do see the file normal, but the IDE which is supposed to load this file, (it's configuration file of a project) is unable to read it (I think it uses some extra encoding or whatever).

However when I replaced it with Set-Content it works fine.

What is a default behaviour of these commands, what Set-Content does differently so that it works in that?

like image 737
Petr Avatar asked Jan 11 '23 00:01

Petr


1 Answers

The difference is in what default encoding is used. From MSDN, we can see that Set-Content defaults to ASCII encoding, which is readable by most programs (but may not work if you're not writing english). The > output redirection operator on the other hand works with Powershell's internal string representation, which is .Net System.String, which is UTF-16 (reference)

As a side-note, you can also use Out-File, which uses unicode encoding.

like image 103
carlpett Avatar answered Mar 04 '23 11:03

carlpett