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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
C:> $Test = "Ryan", "John", "Mark" C:> [String]$Test Ryan Mark John C:> $OFS = "`r`n" C:> [String]$Test Ryan Mark John C:> $OFS = ", " C:> [String]$Test Ryan, Mark, John C:> Remove-Variable OFS C:> [String]$Test Ryan Mark John |
NOTE: The ‘ that you are seeing should be the Backtick key found to the left of your numbers on a US keyboard.
Enjoy!
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?
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.
Nice! This is exactly what I was looking for. Pretty cool little trick.