Coding Ref

String formatting in PowerShell

String formatting in PowerShell

To format a string in PowerShell, you can use the -f operator.

This operator allows you to specify placeholders in the string, and then provide values to be inserted into those placeholders.

Examples

Example 1

Here is an example of how to use the -f operator to format a string in PowerShell:

$myString = "Hello {0}. Today is {1}."

$formattedString = $myString -f "John", (Get-Date)

Write-Host $formattedString

In this example, the -f operator is used to insert the string "John" into the first placeholder {0}, and the current date into the second placeholder {1}.

The resulting formatted string is stored in the $formattedString variable, and is then output to the screen.

Example 2: Format a string with multiple placeholders and values

You can also use the -f operator to format a string with multiple placeholders and values. For example, the following code formats a string with four placeholders and four values:

$myString = "{0} {1} is {2} years old and lives in {3}."

$formattedString = $myString -f "John", "Smith", 35, "New York"

Write-Host $formattedString

In this example, the -f operator is used to insert the string "John Smith" into the first placeholder {0}, the string "Smith" into the second placeholder {1}, the number 35 into the third placeholder {2}, and the string "New York" into the fourth placeholder {3}.

The resulting formatted string is then output to the screen.

Conclusion

To format a string in PowerShell, you can use the -f operator.

This operator allows you to specify placeholders in the string, and then provide values to be inserted into those placeholders.

You'll also like

Related tutorials curated for you

    Piping in PowerShell

    How to use String Contains in PowerShell

    How to make a directory in PowerShell

    What is PowerShell Grep?

    How to unzip a file in Powershell

    How to ping in PowerShell

    How to use SFTP in PowerShell

    How to pause in PowerShell

    Get the full path of ChildItem in PowerShell

    What is WhatIf in PowerShell?

    How to declare global variables in PowerShell

    How to run a .bat file in PowerShell