≡ Menu

Know about $OFS — a special variable in powershell

This is a new thing which I came across today. $OFS is a special variable that contains the string to be used as the Ouptut Field Seperator when an array is converted to a string.  By default, this is ” ” but you can change it.

PS C:temp1>
PS C:temp1> $a=(“a”,”b”,”c”,”d”)
PS C:temp1> $a
a
b
c
d

As you can see in above example, $a is a character array which has a,b,c,d as members. When you print them each character is coming in new line. If I convert this char array to string what is the expected output? “abcd” right? No…you are wrong… see below…

PS C:temp1> [string][char[]]$a
a b c d
PS C:temp1>

There is a space between each character. This happened because $OFS is coming into picture here and inserting a space between each character.

PS C:temp1> $OFS=”/”
PS C:temp1> [string][char[]]$a
a/b/c/d
PS C:temp1>

In the above code I have explicitly changed the $OFS value to “/” which made the conversion to insert a “/” symbol between characters. You can nullify $OFS to avoid any sort of delimiters when you convert a char array to string.

Hope this helps…

{ 1 comment… add one }

Leave a Comment