如何删除 OU 并重新创建它



大家早上好。我目前在学校,从事PowerShell项目。检查是否存在名为"财务"的活动目录组织单位 (OU)。向控制台输出一条消息,指示 OU 是否存在。如果它已存在,请将其删除并向控制台输出一条消息,指出它已被删除。

创建名为"财务"的 OU。将一条消息输出到控制台,说明它已创建。

到目前为止,脚本指出 OU 存在或已创建,但我迷失了如何格式化脚本以使用消息删除 OU,然后使用消息创建 OU。

Try {
Write-Host -ForegroundColor Cyan "[AD]: Starting Active Directory Tasks"
$AdRoot = (Get-ADDomain).DistinguishedName
$DnsRoot = (Get-ADDomain).DNSRoot
$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 "$($OUCanonicalName) Already Exists"
}
}
Catch {
}

谢谢。

你来了:

使用名称财务搜索 OU,如果存在 OU,请将其删除,然后创建它。

#Test if OU exists, current validation is only usefull if the name finance of the ou is unique
$ouName = 'Finance'
$ou = Get-ADObject -LDAPFilter "(&(objectclass=organizationalunit)(name=$ouName))" -ResultSetSize 1 -ResultPageSize 1
If ($ou){
write-host "OU $ouName exists"
#remove OU
try {
Remove-ADObject -Identity $ou.distinguishedname
}
Catch {
write-error "Failed to remove OU: $_"
}
#replace [path] with the disstinguishedname of the parent ou or domain root
try {
New-ADOrganizationalUnit -Name $ouName -DisplayName -ProtectedFromAccidentalDeletion:$false -Path [path]
write-host "OU $ouName created"
}
Catch {
write-error "Failed to create ou: $_"
}
}
Else {
write-host "OU $ouName does not exist"
}

最新更新