Monthly Archive

Categories

PowerShell –f string

A PowerShell –f string is used to format the data inside a string. –f is usually referred to as the format operator.

 

The operation of the format operator is best explained by examples. At its simplest you create fields in the string using {} and the arguments to the right of the –f operator are assigned to those fields in numeric order:

PS> "{0} is  {1}" –f  'A', 'a'
A is  a

 

‘A’ is the first argument (so is assigned to field {0} and so on.

 

You can format the contents of the fields. The full syntax is

{index[,alignment][:format string]}

index is the zero based index of the arguments after the format operator as you’ve seen.

alignment takes a positive number and aligns the item to the right of a field of that length. A negative number produces a left alignment.

PS> "{0,5} is  {1,5}!" -f 'A', 'a'
A is      a!
PS> "{0,-5} is  {1,5}!" -f 'A', 'a'
A     is      a!
PS> "{0,5} is  {1,-5}!" -f 'A', 'a'
A is  a    !
PS> "{0,-5} is  {1,-5}!" -f 'A', 'a'
A     is  a    !

 

The format strings cover numeric and date time formatting

https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

will get you started and provide links to other formatting information

 

A few more examples.

To control the total number of digits displayed

PS> "{0:D3} {1:D3} {2:D3}" -f 2, 20, 200
002 020 200

 

for hexadecimal – case matches case in string

PS> "{0:X4} {1:x8} " -f  1234, 1234
04D2 000004d2

 

Truncating the digits after decimal point

PS> "{0:F3} {1:F2} {2:F1}" -f 2.1234, 3.1234, 4.1234
2.123 3.12 4.1

 

Dates can be manipulated as well

PS> "{0:yyyy} {0:MM} {0:dd} {0:hh} {0:mm} {0:ss}" -f (Get-Date)
2018 01 28 02 24 03

Note that I’m referring to a single object for all of the fields

Comments are closed.