Understanding the –f Operator

by Nov 25, 2015

You may have come across the –f operator before and wondered what it does. It’s the format operator and provides an extremely easy way of accessing array elements to create strings.

Let's start with an array of values, like this one:

$info = 'PowerShell', $PSVersionTable.PSVersion.Major, $pshome

You can now access the individual array elements by index:

 
PS> $info[0]
PowerShell

PS> $info[1]
4

PS> $info[2]
C:\Windows\System32\WindowsPowerShell\v1.0
 

If you wanted to combine the content of this array into a string, this is when the -f operator shines. It lets you use the very same index numbers to access the array elements and put them into a string. Here are a couple of examples that all use the information contained in $info to produce different strings:

 
PS> '{0} Version is {1}. Location "{2}' -f $info

PowerShell Version is 4. Location "C:\Windows\System32\WindowsPowerShell\v1.0

PS> '{0} {1}' -f $info

PowerShell 4

PS> '{0} {1:0.0}' -f $info

PowerShell 4.0

PS> '{0}: {2}' -f $info

PowerShell: C:\Windows\System32\WindowsPowerShell\v1.0
 

Twitter This Tip! ReTweet this Tip!