使用两个 PowerShell 数组重命名 AD 组

Rename AD groups using two PowerShell arrays

我正在尝试以这种方式重命名现有的 AD 组。

以 # 开头的 AD 组将重命名为不带 # 的相同名称。例如,我有 #dl1,我希望将其重命名为 dl1(省略 #)

我先尝试重命名以下四个用户。

我用这种方式写了两个数组。 ($myArray$myArray2)。

$myArray =@(
$data = Get-ADGroup -Filter {name -like "#*"} |select samaccountname
$data.samaccountname |  foreach {$_.split("#")[1]
}
)

$myArray2 =@(
$assdf=Get-ADGroup -Filter {name -like "#*"}
$myArray2 =@($assdf)
$num=0
foreach($a in $assdf)
{
$myArray2[$num] 
$num=$num+1  
}
)

如果我打印 $myarray 它会以这种方式给出我希望的准确结果。

而且如果我打印 $myarray2 它会以这种方式给出所需的结果,

拼图的缺失部分是将这两个数组组合成 运行 最终命令,即

set-adgroup -identity (members indide $myArray2) -samaccountname (members indide $myArray)

几个小时以来,我尝试了很多方法来获取 set-adgroup .. using for each loop 等

例如,

$a=0 

foreach ($item in $myArray2) 
{
  
 
  $nameto_replace=$myArray[$a]
  Set-adgroup -identity $item.samaccountname -samaccountname $nameto_replace
  $a=$a+1

}

任何人都可以解释一下吗?我现在完全没有想法。提前致谢

不需要执行两次 Get-ADGroup,您可以使用它一次并在 ForEach-Object 循环中遍历结果:


根据

更新
Get-ADGroup -Filter "Name -like '#*'" | ForEach-Object {
    $newName = $_.Name.TrimStart('#')
    Write-Host "Renaming group $($_.Name).. to '$newName'"
    # replace only the SamAccountName
    $_ | Set-ADGroup -SamAccountName $newName

    # or replace multiple properties at the same time.
    # You need to use the LDAP names here, so mind the casing !
    # See http://www.selfadsi.org/group-attributes.htm
    # $_ | Set-ADGroup -Replace @{sAMAccountName = $newName; displayName = $newName}
}

如果需要,您可以将搜索限制到指定的 OU,方法是使用 -SearchBase 参数添加 OU 的可分辨名称

Theo 的回答太棒了!

以下是我最后使用的来自theo的答案。

Get-ADGroup -Filter "Name -like '#*'" | ForEach-Object {
$newName = $_.Name.TrimStart('#')

$_ | Set-ADGroup -Replace @{sAMAccountName = $newName;displayName = $newName} 

$_ | Rename-ADObject -NewName $newName
}

如果您尝试使用 set-adgroup 更改 'name''CN' 并且它给出低于错误。

"Set-ADGroup : The directory service cannot perform the requested operation on the RDN attribute of an object"

改变多个属性,特别是NameCNRename-ADObjectSet-ADGroup的组合可以被使用。