How to Insert Character into String in PowerShell (With Examples)


Often you may want to insert a character into a specific position of a string in PowerShell.

You can use the following methods to do so:

Method 1: Insert One Character into String

$my_string = $my_string.Insert(6, ' ')

This particular example inserts a space into index position 6 of the string named $my_string.

Method 2: Insert Multiple Characters into String

$my_string = $my_string.Insert(6, ' ').Insert(11, ' ')

This particular example inserts a space into index position 6 and a space into index position 11 of the string named $my_string.

By using the Insert() method twice, we’re able to insert two characters in specific positions of the string at once.

Note: The Insert() method does not modify the string in-place, which is why we must assign the changes back to the original variable name.

The following examples show how to use each of these methods in practice.

Example 1: Insert One Character into String in PowerShell

Suppose that we have a variable named $my_string in PowerShell that contains the following string:

  • DallasMavsTeam

Suppose that we would like to insert a single space into index position 6 of the string to produce the following new string:

  • Dallas MavsTeam

We can use the following syntax with the Insert() method to do so:

$my_string = 'DallasMavsTeam'
$my_string = $my_string.Insert(6, ' ')

The following screenshot shows how to use this syntax in practice:

PowerShell insert character into specific position of string

Notice that a single space has been inserted into index position 6 of the string.

Example 2: Insert Multiple Characters into String in PowerShell

Once again, suppose that we have a variable named $my_string in PowerShell that contains the following string:

  • DallasMavsTeam

Suppose that we would like to insert a single space into index position 6 and position 11 of the string to produce the following new string:

  • Dallas Mavs Team

We can use the following syntax with the Insert() method to do so:

$my_string = 'DallasMavsTeam'
$my_string = $my_string.Insert(6, ' ').Insert(11, ' ')

The following screenshot shows how to use this syntax in practice:

PowerShell insert multiple characters into multiple positions of string

Notice that a single space has been inserted into both index positions 6 and 11 of the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Trim Leading Spaces from String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Only Numbers from String

Leave a Reply