Using -f Operator to Combine String and Data

by Sep 2, 2014

All PowerShell Versions

Strings enclosed by double-quotes will resolve variables so it is common practice to use code like this:

$name = $host.Name
"Your host is called $name." 

However, this technique has limitations. If you wanted to display object properties and not just variables, it fails:

 
PS> "Your host is called $host.Name."
Your host is called System.Management.Automation.Internal.Host.InternalHost.Name. 

This is because PowerShell only resolves the variable (in this case $host), not the rest of your code.

And you cannot control number formats, either. This line works, but the result simply has too many digits to look good:

# get available space in bytes for C: drive
$freeSpace = ([WMI]'Win32_LogicalDisk.DeviceID="C:"').FreeSpace

# convert to MB
$freeSpaceMB = $freeSpace / 1MB

# output
"Your C: drive has $freeSpaceMB MB space available." 

The –f operator can solve both problems. It takes a static text template to the left, and the values to insert to the right:

# insert any data into the text template
'Your host is called {0}.' -f $host.Name 


# calculate free space on C: in MB
$freeSpace = ([WMI]'Win32_LogicalDisk.DeviceID="C:"').FreeSpace
$freeSpaceMB = $freeSpace /1MB

# output with just ONE digit after the comma
'Your C: drive has {0:n1} MB space available.' -f $freeSpaceMB

As you see, using -f gives you two advantages: the placeholders (braces) tell PowerShell where insertion should start and end, and the placeholders accept formatting hints, too. "n1" stands for numeric data with 1 digit. Simply change the number to suit your needs.

Twitter This Tip! ReTweet this Tip!