Alex Edwards Alex Edwards - 1 year ago 78
PowerShell Question

Replacing Numeric Characters through Indexing

I'm attempting to replace a character within a string, which in this case is a digit, with another digit that has been incremented by 1, and then adding it back to the original string and replacing the previous digit character.

In the below snippet,

should become
after this code has executed

However, I keep receiving the error,
Unable to index into an object of type System.String.
Is it not possible to replace characters through indexing? Is there a better methodology for something like this?

$SAMAccountName = "sams2"
$lastChar = $SAMAccountName.Length - 1

[int]$intNum = [convert]::ToInt32($SAMAccountName[$lastChar])
$convertedChar = [convert]::ToString($intNum + 1)
$SAMAccountName[$lastChar] = $convertedChar

Answer Source

Ok, this is a two step process. First we get the number off the end, then we replace that number in the string.

'sams2' |%{
    $Int = 1+ ($_ -replace "^.*?(\d+)$",'$1')
    $_ -replace "\d+$",$Int