PowerShell string manipulation

Hi all

I am having an issue trying to do some basic string manipulation if I have a simple string like

$a="1234567890"

I would like to change say the value of the sixth character regardless of the value. I can’t seem to get the proper format to accomplish this.

Any help would be appreciated.
Thanks
Tim

Try this, where 8 is the value replacing the 6th character in the $a variable:

$a.Replace($a[5],"8")

#OR

$a -Replace $a[5],"8"

Note that with the .Replace() method, you can only replace the character with a single character, like in the example I gave above. Using the -Replace operator, you can replace the single character with a string.

Also, the .Replace() method and -Replace operator will replace all instances of the character you’re trying to replace. So, if $a = “12345678690”, then if you replace the 6th character, which is a 6 in the string, all 6s will be replaced (example, with the letter ‘r’).

12345678690 becomes 12345r78r90

If you want to make sure you only replace that once instance of whatever is the 6th character(index = 5), then you can do the following.

$a = $a.Substring(0,4),'CharacterOrStringYouWantToReplaceThe6thCharacterWith',$a.Substring(6,$a.Length - 6) -join ""

Another option.

$a = '1234567890'
$a.Remove(5,1).Insert(5,"a")

Good to know. :slight_smile:

Great thanks a lot guys, I appreciate it. @Curtis That one was great, it was exactly what I have been looking for.