如何在PowerShell中删除并重新创建Active Directory的Finance OU
PowerShell AD OU 存在检查、删除重建脚本修改
需求说明
检查名为“Finance”的Active Directory Organizational Unit(OU)是否存在,控制台输出存在/不存在提示;若该OU已存在,则删除它并输出删除提示,随后重新创建同名OU并输出创建提示。
现有脚本问题
当前脚本仅能判断OU是否存在并直接创建,无法实现“存在则删除后重建”的逻辑。
修改后的完整脚本
Try { Write-Host -ForegroundColor Cyan "[AD]: Starting Active Directory Tasks" $AdRoot = (Get-ADDomain).DistinguishedName $OUCanonicalName = "Finance" $OUDisplayName = "Finance" $ADPath = "OU=$($OUCanonicalName),$($AdRoot)" if (-Not([ADSI]::Exists("LDAP://$($ADPath)"))) { New-ADOrganizationalUnit -Path $AdRoot -Name $OUCanonicalName -DisplayName $OUDisplayName -ProtectedFromAccidentalDeletion $false Write-Host -ForegroundColor Cyan "[AD]: $($OUCanonicalName) OU Created" } else { Write-Host -ForegroundColor Yellow "[AD]: $($OUCanonicalName) Already Exists" # 删除已存在的OU,-Recursive处理子对象,-Confirm:$false跳过确认提示 Remove-ADOrganizationalUnit -Identity $ADPath -Recursive -Confirm:$false Write-Host -ForegroundColor Red "[AD]: $($OUCanonicalName) OU Deleted" # 重新创建OU New-ADOrganizationalUnit -Path $AdRoot -Name $OUCanonicalName -DisplayName $OUDisplayName -ProtectedFromAccidentalDeletion $false Write-Host -ForegroundColor Cyan "[AD]: $($OUCanonicalName) OU Recreated" } } Catch { Write-Host -ForegroundColor Red "[AD]: Error occurred - $($_.Exception.Message)" }
关键改动说明
- 在
else分支中新增删除逻辑:使用Remove-ADOrganizationalUnit删除目标OU,添加-Recursive参数确保删除OU包含的所有子对象,-Confirm:$false参数避免执行时弹出确认提示 - 补充删除、重建对应的彩色提示信息,保持日志风格统一
- 完善Catch块,输出具体错误信息便于排查问题
内容的提问来源于stack exchange,提问作者Dre45
相关产品推荐
相关产品推荐

