Viewing entries tagged
format_operator

PowerShell Quick Tip: Basic use of the -f format operator

PowerShell Quick Tip: Basic use of the -f format operator

What the -f?

There are many ways to manipulate/build strings in PowerShell. One of my favorite ways is to use the -f format operator. When you use the operator, it evaluates everything to the right of -f as an array that starts at index value 0 (as all PowerShell arrays do). The values are comma separated.

Setup

For this demonstration I setup the following variables:

[array]$formatArray = @('you','values','them.')
$user               = (Get-ChildItem Env:\USERNAME).Value
$date               = Get-Date

Using the -f operator

Example one

"Your user name is {0}, and the time is [{1:HH}:{1:mm}:{1:ss}]" -f $user,$date

Returns

Your user name is Mike, and the time is [12:54:44]

Example two

Since it is indexing values as an array (starting at zero), you can actually feed it an array. Let's look at the values of the $formatArray array.

0 = you
1  = values
2 = them

Knowing that now, let's run this command:

"These {1} go where {0} place {2}" -f $formatArray

Returns

These values go where you place them.

Pretty cool, huh? There are multiple uses for this! Here is one example from a logging module I wrote. The context here is the user used the -addDate $true argument, and I need to append the date to the log name.

    if ($addDate) {
        
        if ($logName.Contains('.')) {
            
            $logName = $logName.SubString(0,$logName.LastIndexOf('.')) + "_{0:MM-dd-yy_HHmm}" -f (Get-Date) + $logName.Substring($logName.LastIndexOf('.'))
            
            Write-Verbose "Adding date to log file with an extension! New file name: $logName"
            Write-Verbose ""
           
        } else {
            
            $logName = $logName + "_{0:MM-dd-yy_HHmm}" -f (Get-Date)
            
            Write-Verbose "Adding date to log file. New file name: $logName"
            Write-Verbose ""
            
        }
         
    }

But wait... there's more!

As you can see in the examples above you can use the value with a colon and then specify more options. For these examples I used the options for getting specific values returned by Get-Date such as:

{1:HH}:{1:mm}:{1:ss}

This allows us to enumerate the values specifically for the 24 hour hour, minutes, and seconds returned by $date (which is where Get-Date is stored from the setup above).

There are other options you can use to to further format your strings. There are ones for different placements, spaces, and even returning different number values.  To check out the full details of what the -f format operator can do, check out these links!

As always, let me know if you have any questions or ideas in the comments section below!

-Ginger Ninja