Concatenate String in PowerShell

Using Operators

To concatenate string in PowerShell:

  • Declare and initialize variables which contain string-type values.
  • Use +, -f, and -join operators to concatenate values of all variables we created in the first step.

We can use the +, -f, and -join operators to concatenate strings with/without separators in PowerShell. Let’s understand the use and difference of these operators below.

First, we declared and initialized three variables, $greetings, $first_name, and $last_name containing Hi, Mehvish, and Ashiq values, respectively.

Note that PowerShell variables are prefixed with a $ sign, for example, $VariableName.

Next, we used the + operator to concatenate values of all variables with/without a separator. We used a single space to separate one string from the other; you can use any other separator, for instance, a comma, a semi-colon, a hyphen, etc.

After that, we used the -f operator (format operator), which acts like the + operator and concatenates the values of $greetings, $first_name, $last_name variables by placing them at index 0, 1, and 2 respectively. However, it differs from the + operator because it allows us to have strings on specific indexes by changing the position of variables.

We can put a white space between each curly bracket pair to separate strings one from the other. The numbers wrapped around the curly brackets are the indexes. We can change the order of values without re-arranging variables as follows.

The third operator that we used was the -join operator; it also works like + and -f operators; the good thing with the -join operator is that we don’t have to write separator repeatedly, but we pass it once after -join parameter.

We saved the results in $plus_without_separator, $plus_with_separator, $f_without_separator, $f_with_separator, $join_without_separator, $join_with_separator variables that we got after using +, -f, and -join operators with and without a separator.

We can write these variables individually on the PowerShell console to display the output, but we adopted a different approach to have a look at all the outcomes simultaneously. For that, we used @{} to create a hash table, which is a data structure with unique keys to specific values; we used it to have properties in key-value format.

Next, we enclosed the @{} with $([ordered]) as $([ordered]@{}) to have properties in the order in which they are created; otherwise, they would be displayed randomly. See the following output to have a clear picture.

At this point, we created an object with all the properties we defined using a hash table and saved it in the $props variable. How? Let’s have a look at that. The New-Object created an object while the -Property parameter set every property value and invoked every method of the newly created object in the order in which they appeared in the hash table.

Remember, the hash table contains data in a key-value format where a key is the name of a method or property while the value is the method argument or property value. So now, the point is, why are we using the PSObject class?

We used the PSObject class because if a new object was derived from the PSObject class, and we write a property which doesn’t exist on that object, the New-Object will add our specified property to our object as NoteProperty. So for this particular situation, the New-Object command will produce a non-terminating error if we don’t use the PSObject class.

We saved our object’s data in the $result array that we created using the array operator (@()), and finally, we used the Write-Output cmdlet to print the values of the specified variable on the PowerShell console.

Note that the Write-Output will send the objects to a primary pipeline called Output Stream or Success Pipeline. This cmdlet is used to display objects and strings on the PowerShell console. For example, if we had an error, we would use Write-Error to send error objects to an error pipeline.

Using Built-in Functions

To concatenate string in PowerShell:

  • Declare and initialize three variables which contain string-type values.
  • Use concat(), Join(), and Format() functions to concatenate values of all variables we created in the first step.

We’ve already learned this code in detail while using it with operators (+, -f, and -join) in the [first section](add link of the first H2). This code example and its logic is the same as we used in the previous section except for one difference, we used built-in functions here.

In PowerShell, the built-in functions concat(), Join(), and Format() can be used to concatenate strings where concat() acts like + operator, Join() behaves like -join() operator and Format() acts like -f operator.

There are only two advantages to using these methods. First, we have more organized code, and second, we don’t have any limit on the number of strings for concatenation.

Using Operators/Functions to Concatenate Strings with Numbers

To concatenate string in PowerShell:

  • Declare and initialize two variables; one holds a numerical value, and the other contains a string type value.
  • Use +, -f, and -join operators to concatenate values of all variables we created in the first step.

We have already learned about the +, -f, and -join operators, the logic of the above code and its working while using operators to concatenate strings in the first section.

Here, we used these operators to concatenate numerical values with string-type values. Note that there won’t be any error if we put integer type variables in first or last place while concatenating. We can use built-in functions as follows to concatenate strings with numerical values.

Using StringBuilder

To concatenate String in PowerShell:

  • Create a new object of type System.Text.StringBuilder.
  • Use append() method to append String to it.
  • Use ToString() method to convert it back to String.

New-Object cmdlet is used to create an instance of a Microsoft .NET Framework or COM object. We specified -TypeName as System.Text.StringBuilder to create StringBuilder type of object.

We used append() method to add $first_name and $last_name to the StringBuilder object and used ToString() method to convert it to String.

That’s all about how to Concatenate String in PowerShell.

Was this post helpful?

Related Posts

  • Convert Month name to number in PowerShell
    23 January

    Convert Month Number to Name in PowerShell

    Table of ContentsUsing the Get-Culture() CmdletConvert the Hardcoded Month Number to the NameConvert the Month Number from a Date to the NameConvert the Current Month Number to the NameUsing the [cultureinfo]::InvariantCulture Property Using the Get-Culture() Cmdlet We can use the Get-Culture cmdlet in the following three possible ways: To Convert the Hardcoded Month Number to […]

  • Delete empty folders in PowerShell
    23 January

    Delete Empty Folders in PowerShell

    Table of ContentsUsing the Remove-Item with Get-ChildItem CmdletUsing the Get-ChildItem and ForEach-ObjectUsing the User-defined Function There are multiple ways that we can use to delete the empty folders in PowerShell but before going into the details, let’s have a look at the following directory structure to know how many and which folders are empty. [crayon-63d19abea452f156710633/] […]

  • PowerShell- Where-Object with multiple conditions
    23 January

    PowerShell – Where-Object with Multiple Conditions

    Table of ContentsUsing Where-Object Cmdlet with Multiple ConditionsScript BlockComparison Statements Using Where-Object Cmdlet with Multiple Conditions In PowerShell, we have various comparison and logical operators that we can use with the Where-Object cmdlet to apply multiple conditions. Let’s explore a few scenarios below. [crayon-63d19abe9cb1d585054535/] [crayon-63d19abe9cb23269289589/] The above command returned an item where the extension of […]

  • Rename Files with PowerShell
    18 January

    Rename Files with PowerShell

    Table of ContentsRename Single File with PowerShellUsing Rename-Item with/without the -Path ParameterUsing Rename-Item with -Confirm ParameterUsing Rename-Item with -Passthru ParameterRename multiple files in PowerShell Rename Single File with PowerShell Using Rename-Item with/without the -Path Parameter Use the Rename-Item cmdlet to rename a file in PowerShell. [crayon-63d19abea46fa885505211/] We used the Rename-Item cmdlet to rename the test.txt […]

  • PowerShell - redirect output to File
    18 January

    PowerShell – Redirect Output to File

    Table of ContentsUsing Out-File CmdletUsing Redirection OperatorsUsing StreamWriter .Net ClassUsing Add-Content CmdletUsing Set-Content Cmdlet Using Out-File Cmdlet Use the Out-File cmdlet to redirect PowerShell output to a file. [crayon-63d19abe9c935390050111/] The Get-Process is used to retrieve all the processes that are currently running on our machine (local computer). We can filter this information by specifying parameters; […]

  • PowerShell - Logical operators
    18 January

    PowerShell – Logical Operators

    Table of ContentsUsing Logical Operators in PowerShellUse Logical AND OperatorUse Logical OR OperatorUse Logical EXCLUSIVE OR OperatorUse Logical NOT OperatorUse Multiple Logical Operators Using Logical Operators in PowerShell PowerShell’s logical operator is a potent tool for comparing data and carrying out operations depending on those comparisons. It allows the user to design an if-then scenario […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.