Use PowerShell to Format Strings with Composite Formatting

Use PowerShell to Format Strings with Composite Formatting

  • Comments 4
  • Likes

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to specify composite formatting to format strings.

Hey, Scripting Guy! Question Hey, Scripting Guy! Often I need to create an output string that is the result of multiple computations. In the past, I have used multiple lines to create this sort of outputs, but now I would like to simplify the process. Do you have any suggestions?

—DB

Hey, Scripting Guy! Answer Hello DB,

Microsoft Scripting Guy, Ed Wilson, is here. Ah, now I can enjoy a nice cup of tea. I am sipping a cup of Lapsang Sochong tea. I generally add milk to the tea and use a bit of honey with it. To me the milk and honey mix well with the smoky flavor of the tea.

Note   This is the second blog post in a series of five that talk about using format methods and operators in Windows PowerShell. The first blog, Understanding PowerShell and Basic String Formatting, provided a great overview to the basics of using the Format method from the String class and the Format operator from Windows PowerShell for composite formatting.

Formatting objects in strings

The first thing I want to talk about today is using format specifiers to control the way that certain objects display. The format item syntax of this technique is shown here:

{index:formatString}

Note   For reference information about this technique, see Composite Formatting on MSDN.

Using format strings with composite formatting

Many of the format specifiers are usable directly within the format item. The following examples illustrate using this technique. The first example illustrates using the WriteLine static method from the System.Console .NET Framework class. The second method illustrates performing the same task by using the format operator from Windows PowerShell, and the last example illustrates using the Format static method from the System.String .NET Framework class. The Windows PowerShell format operator and the Format static method were illustrated in yesterday’s Hey, Scripting Guy! Blog, Understanding PowerShell and Basic String Formatting.

Example 1: Use format string with the WriteLine static method

The WriteLine static method from the System.Console .NET Framework class writes directly to the Windows PowerShell console. It does not send objects down the pipeline. This behavior is the same as using the Write-Host cmdlet. The command shown here uses a format item that that specifies the index of 0 for the first item, and a format string of C. The C format string is a Standard Numeric Format String, and it is the Currency Format Specifier. The object supplied to the format item is the number 100. Following is the code and the output associated with the code.

PS C:\> [console]::writeline("The price is {0:C}", 100)

The price is $100.00

Example 2: Use format string with the Windows PowerShell format (-f) operator

The format operator, -f, places the composite formatting with the format item on the left side of the -f operator and the object list on the right side of the -f operator. The format item uses the same format string, and the same value supplies the format item. Following is the code and the output associated with the code.

PS C:\> "The price is {0:C}" -f 100

The price is $100.00

Example 3: Use the format string with the Format static method

The Format static method from the string class works exactly the same as the WriteLine method from the System.Console .NET Framework class with one important exception: It returns a string. It will send a string down the Windows PowerShell pipeline. Other than that, the format item is the same, and the output appears the same. The command and the output associated with the code are shown here.

PS C:\> [string]::Format("The price is {0:C}",100)

The price is $100.00

Using the alignment component

To provide for the formatting of output within “cells,” I use the alignment component of the format item. The alignment component is optional, as seen in the three earlier examples that did not include the alignment component. The alignment is a signed integer that specifies the preferred field width. If the value of the alignment is smaller than the actual length of the formatted string, the value of the alignment component is ignored. Alignment to the right takes place if the value of the integer is positive. Alignment to the left takes place if the integer is negative. The following examples illustrate various ways of using the alignment component.

Example 4: Align a date with a string

Here I store a string in a variable. Next I call the WriteLine static method from the System.Console .NET Framework class. The format item substitutes the first object (the $attendee variable value) at the beginning of the output string. Next I use a string literal (attended), and I use the standard Windows PowerShell “carriage return and line feed” (`r`n) characters to move the output to the second line. Now I specify the second substitution object, which is the result of using the Get-Date cmdlet (turning it into a string) and using the d. The d  standard format specifier represents a custom date time format that is culture specific. It provides a short date pattern in the pattern that is defined by the current culture settings.

In the second format item, after specifying the second object, a positive 18 appears. This is shown here.

 {1,18}

The  positive 18 means to space over 18 spaces from the left. This code and its associated output are shown here.

PS C:\> $attendee = "Ed Wilson"

PS C:\> [console]::Writeline("{0} attended `r`n{1,18}", $attendee, (Get-Date).tostring('d'))

Ed Wilson attended

          3/7/2013

Example 5: Short way to align a date with string

In this example I do basically the same thing as I accomplished in Example 4. So I am not going to repeat everything from that example. The big difference here is in the second format item. I use a third position to specify the d short date format specifier. This permits greater simplicity of the code that I used in Example 4. By using this third position, I am able to tell the object returned by Get-Date to display in short date format. Therefore, I avoid the ToString method call and using the d short date specifier there. As shown here, the output is the same—the only change is in the second format item and the call for the second object (highlighted in red).

[console]::Writeline("{0} attended `r`n{1,18:d}", $attendee, (Get-Date))

PS C:\> $attendee = "Ed Wilson"

PS C:\> [console]::Writeline("{0} attended `r`n{1,18:d}", $attendee, (Get-Date))

Ed Wilson attended

          3/7/2013

DB, that is all there is to using composite formatting and specifying additional parameters. Formatting Week will continue tomorrow when I will talk about formatting numbers.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • @Ed - perfect. You hit almost all of the most used features.

  • @JRV Thanks! These are powerful techniques, but I am not done yet... Still more to come the rest of the week :-)

  • Very hard to equate to printf formatting, and to align on columns where variables are different lengths ?