Forum Discussion

Dre45's avatar
Dre45
Copper Contributor
Oct 10, 2022
Solved

New PowerShell user question

Good afternoon everyone.   Doing a task for an assignment and I can get the below to answer if the Finance OU is created or not. How could I structure my next if/else statement to delete the OU if ...
  • Harm_Veenstra's avatar
    Oct 10, 2022

    Dre45 Just an example, if checks if the OU exists and if it does, it removes it and recreates it at the same location:

     

    $OUName = 'Finance'
    #Check if $OUName exists and record location in $oulocation
    try {
        $OUlocation = Get-ADOrganizationalUnit -Filter 'Name -like $OUName' -Properties * -ErrorAction Stop
        Write-Host ("{0} OU does exist, receating..." -f $OUName) -ForegroundColor Green
    }
    #Exit script if it doesn't exist
    catch {
        Write-Warning ("{0} OU does not exist" -f $OUName)
        break
    }
    
    #Remove Protected Setting from OU, remove OU, recreate in Original location
    try {
        Set-ADOrganizationalUnit -Identity $OUlocation.DistinguishedName -ProtectedFromAccidentalDeletion:$false -Confirm:$false -ErrorAction Stop
        Remove-ADOrganizationalUnit -Identity $OUlocation.DistinguishedName -Confirm:$false -ErrorAction Stop
        New-ADOrganizationalUnit -Name $OUlocation.Name -DisplayName $OUlocation.DisplayName -Path ($oulocation.DistinguishedName -replace '^.+?,(CN|OU.+)', '$1') -ErrorAction Stop
        Write-Host ("Recreated the {0} OU" -f $OUName) -ForegroundColor Green
    }
    #Display warning if there was an error recreating OU
    catch {
        Write-Warning ("Error creating {0}" -f $OUName)
    }

Resources