Inserting Text into String

by Apr 15, 2016

Use Insert() to insert new text into an existing string at a given position. Here is an example:

$text = "Server failed"


1..100 | ForEach-Object { $text.Insert(6, $_) }

It produces a list of servers with an increment. Of course, this particular problem could have solved differently with PowerShell because you can insert variables directly:

1..100 | ForEach-Object { "Server $_ failed" }

However, when you have text that you do not control, for example file names or CSV content, then Insert() is a great alternative.

Twitter This Tip! ReTweet this Tip!