You can use the -replace
operator for this and make it vary as necessary:
# Replaces three characters before a final character of )
$replace = 'ICC'
Set-aduser -Identity $_.SamAccountName -Replace @{DisplayName=$_.DisplayName -replace '.{3}(?=\)$)',$replace}
Explanation:
-replace
uses regex matching and replaces the match with a replacement string. The replacement string can be a literal string, contain variables, or capture groups matched by the regex portion.
.
is any single character. {3}
matches exactly three times. (?=)
is a positive lookahead assertion, which the means the future characters match what is inside from the current position. Lookahead allows for a match that isn't captured and therefore it is not output and not replaced. $
means the end of the string. \)
is backslash escaping a literal )
. Since (
and )
have special meaning in regex, they must be escaped.
Sometimes you may not know the last character. In that case, you can use the following to replace the three characters before a final arbitrary characters:
$replace = 'ICC'
Set-aduser -Identity $_.SamAccountName -Replace @{DisplayName=$_.DisplayName -replace '.{3}(?=.$)',$replace}
If you wanted to replace the final three characters regardless of their value, you can do the following:
$replace = 'ICC'
Set-aduser -Identity $_.SamAccountName -Replace @{DisplayName=$_.DisplayName -replace '.{3}$',$replace}
If you wanted to replace the final three consecutive alpha characters even if they are far from the end of the string, you can do:
$replace = 'ICC'
Set-aduser -Identity $_.SamAccountName -Replace @{DisplayName=$_.DisplayName -replace '[a-z]{3}(?=[^a-z]*$)',$replace}