Welcome to the navigation

Irure eu ipsum ea sunt adipisicing aliqua, cillum id et elit, minim quis ad eiusmod sed esse proident, cupidatat fugiat sint culpa sit exercitation ex. Duis nulla ex magna voluptate ut pariatur, velit dolor occaecat cillum fugiat ipsum ea aute excepteur adipisicing aliqua, nostrud reprehenderit est ut lorem in exercitation

Yeah, this will be replaced... But please enjoy the search!

String concatenation in PowerShell

Strings concatenation in PowerShell is an everyday task for almost any Windows IT staff or Microsoft platform developer today. There are a few ways to accomplish this

Our variables

$hello = "Hello"
$world = "World"

The ordinary usage

Using built-in methods in PowerShell

# Concatenated using +
$concatenatedString = $hello + " "  + $world  +  "!"
 
# Using embedded variables
$embeddedString = "$hello $world!"
 
# Using string.Format powershell version (-f for format)
$formattedString = "{0} {1}!" -f $hello, $world

Using native .net methods

# Using string.Concat
$concatenateString = [System.String]::Concat($hello, " ", $world, "!")
 
# Using string.Format
$formattedString = [System.String]::Format("{0} {1}!", $hello, $world)

Preference

That is up to you, performance-wise there is little or no difference when doing a million cycles. My personal preference would be the native .net methods since thats what I'm used to read and I like to keep things simple.

What will happend with line breaks using the different methods

Concatenated using + with line breaks

$concatenatedString = $hello + 
    " "  + 
    $world  +  
    "! "

Returns the entire string in one line

Hello World!

Using embedded variables

$embeddedString = 
    "$hello 
    $world!"

Returns a line broken string

Hello 
    World!

Using string.Format powershell version (-f for format)

$formattedString = "{0} 
    {1}!" -f $hello, $world

Returns a line broken string

Hello 
    World!

Using string.Concat

$concatenateString = 
    [System.String]::Concat($hello, 
        " ", $world, 
        "!")

Returns the entire string in one line

Hello World!

Using string.Format

$formattedString = 
    [System.String]::Format(
        "{0} {1}!", 
        $hello, $world)

Returns the entire string in one line

Hello World!

Using string.Format

$formattedString = 
    [System.String]::Format(
        "{0} 
        {1}!", 
        $hello, $world)

Returns a line broken string

Hello 
        World!
Enjoy