0

I am attempting to change 3 characters for a list of users. all these users have a bit appended on their DisplayName (ABcD-somthing) i want to change that something to (ABcD-ICC) I was going to use

Set-aduser -Identity $_.SamAccountName -Replace @{DisplayName="$_.Surname, $_.GivenName (ABcD-ICC)"}

But the only thing I would be changing is the ICC at the very end. is there an easier way to do that?

BPengu
  • 92
  • 8

1 Answers1

0

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}
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27