Wednesday, June 10, 2015

#84 : Difference between redirection operator and Out-File

Redirection operator can be used most of the scripting languages. If you use single redirection operator (>), it means create a file and write or overwrite the file with the string.
In Powershell, you can use them, but we have advantage of Out-File cmdlet. Let us try to see what is major difference. The difference is that redirection operator will always go with unicode character.

For example:
echo "Line - 1" > c:\temp\file.ps1 
echo "Line - 2" >> c:\temp\file.ps1 
It will generate a file with Unicode character set.

Repeating the same with Out-File :
echo "Line - 1" | Out-File c:\temp\file.ps1 -Encoding "ASCII" 
echo "Line - 1" | Out-File c:\temp\file.ps1 -Encoding "ASCII" -Append 
It will generate a file with ASCII character set.

Mind that we have use -Append in the second line. This will allow appending. Check yourself that what will happen if you don't use -Append switch.

There are below character sets possible with -Encoding option:
Unicode
UTF7
UTF8
UTF32
ASCII
BigEndian
Unicode
OEM

If you don't mention Encoding switch, Unicode will be taken as default.


Don't mix character set if you don't want to see unexpected graphics in file. For example, if you run below lines, you will understand what I mean.

echo "Som" > file.txt
echo "Som" | out-file .\file.txt -Encoding "ASCII" -Append

When you open file.txt, you would see first line written correctly and second line written in chinese. I have faced such situations where output is coming from multiple command line apps like osql and sqlplus and mixing them together created a real mess. The difficult part is that you can barely troubleshoot where problem is coming from. Try to stick to ASCII in my opinion.

Thanks for reading this article!
 

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...