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!

  3 Responses to “Quick Tip: Newlines when Typecasting Arrays to Strings”

  1. This is very interesting… I can’t believe I’ve never seen this before.

    Lately, to convert and format a string array to a single string, I’ve been using something like the following:
    @(“string1″,”string2″,”string3”) -join “, ”

    I wonder which is actually more efficient or what cases modifying the $OFS would be more ideal?

  2. That’s a cool little trick, but it’s also an example of some of the poor design in powershell: there’s nothing that suggests that “OFS” as a variable is used for something like formatting arrays cast as strings – unless you dig really deep into the documentation. You know that someone, somewhere, is going to use OFS like a normal variable, and then get a big surprise when something blows up later in the script.

    Of course, if you’re using three-lettered variable names on a regular basis, your scripting probably has bigger problems.

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

Leave a Reply to Taylor Harris Cancel reply

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=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

(required)

(required)

This site uses Akismet to reduce spam. Learn how your comment data is processed.