Aug 302012
 

Converting arrays into strings can cause a couple different problems, and I am starting to see more and more people struggling. The problem is that it doesn’t always act like you think it should. By default, converting an array into a string will place every item on one line of text separated by a space. This is particularly true with arrays made by get-content that are typecast into a string.

The answer is very simple. When you type cast an array into a string every field is separated by a secret value (not so secret anymore!) called the Object Field Separator, or OFS. This value is keep in a variable called $OFS and you can change it! For instance, if you want there to be a new line when you typecast the array then set $OFS = "`r`n" which will make a newline between every field. If you want to comma separate the values, then set $OFS = ", "

Just remember to clean up when you are done! You can set the value back to it’s default (a single space) by removing the variable: Remove-Variable OFS Don’t worry, PowerShell will remake it.

NOTE: The ‘ that you are seeing should be the Backtick key found to the left of your numbers on a US keyboard.

Enjoy!

  One Response to “Quick Tip: Newlines when Typecasting Arrays to Strings”

  1. Nice! This is exactly what I was looking for. Pretty cool little trick.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">