Good morning everyone. I am currently in school, working on a PowerShell project. Check for the existence of an Active Directory Organizational Unit (OU) named “Finance.” Output a message to the console that indicates if the OU exists or if it does not. If it already exists, delete it and output a message to the console that it was deleted.
Create an OU named “Finance.” Output a message to the console that it was created.
This what I have so far, the script states that either the OU exists or that it was created but I'm lost at to how to format the script to delete the OU with a message and then create the OU with a message.
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 {
}
Thank you.
CodePudding user response:
Here you go:
Search for OU with Name Finance, if OU exists remove it and then create it.
#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"
}