Skip to content

Instantly share code, notes, and snippets.

@mbrownnycnyc
Created December 19, 2018 20:56
Show Gist options
  • Save mbrownnycnyc/ae50c08ffa44a912a14b647bed72d1be to your computer and use it in GitHub Desktop.
Save mbrownnycnyc/ae50c08ffa44a912a14b647bed72d1be to your computer and use it in GitHub Desktop.
rename all groups in an OU, replacing a specific string
function renamegroupsin-ou{
[cmdletbinding()]
param (
$targetou,
$findpattern,
$replacepattern
)
$groups = get-adobject -searchbase $targetou -ldapfilter “objectClass=group” -properties samaccountname, cn
foreach ($group in $groups) {
#perform string replace
$oldadgroupcn = $group.cn
$oldsamgroupname = $group. samaccountname
$newadgroupcn = $oldadgroupcn -replace “$findpattern”, “$replacepattern”
$newsamgroupname = $oldsamgroupname -replace “$findpattern”, “$replacepattern”
try {
set-adobject -identity $($group. distinguishedname) -replace @{ samaccountname=”$newsamgroupname” } rename-adobject -identity $($group. distinguishedname) -newname “$newadgroupcn”
} catch {
write-host “set action failed: $($group.distinguishedname)”
$_. exception
}
}
}
function main {
renamegroupsin-ou -targetou “OU=Server2,OU=contosoNYC,DC=contoso,DC=com” -findpattern ““ -replacepattern “-“
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment