Rename users / Searching and replacing with regex


posted by mpetka
02-25-2013

Downloads: 188
File size: 386 B
Views: 1,288

Embed
Rename users / Searching and replacing with regex
  1. $regex = '(?<=CN=)[A-Z][a-z]*\s\([A-Z][a-z]*\)\s[A-Z][a-z]*' 
  2. $regexr = '\s\([A-Z][a-z]*\)' 
  3. $Users = Get-ADUser -Filter {Enabled -eq "True"} -Properties DistinguishedName, name, displayname | Where-Object { $_.DistinguishedName -match $regex
  4. ForEach ($User In $Users
  5.     $NM = $User.Name 
  6.     $NR = $NM -Replace $regexr,"" 
  7.     Rename-ADObject -Identity $user -NewName $NR 

I needed to clean up some usernames that had been created in the form "Johnny (John) Smith">  Get-ADUser -Filter {name -like "*(*)*"} got me close but I needed more precision. Regex provided great control. 

Copyright 2012 PowerShell.com. All rights reserved.