PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

image rotation

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Using -f Operator to Combine String and Data

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!

Copyright 2012 PowerShell.com. All rights reserved.