private/DeleteOUSubtreeWithConfirm.ps1

Function DeleteOUSubtreeWithConfirm {
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='high')]
    Param
    (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [String]$path,
        [Microsoft.ActiveDirectory.Management.ADDirectoryServer]$Server = (get-addomainController -Writable -Discover)
    )

    PROCESS {
        $shouldProcess = @{
            Confirm = [bool]($ConfirmPreference -eq "low")
            Whatif = [bool]($WhatIfPreference.IsPresent)
            verbose = [bool]($VerbosePreference -ne "SilentlyContinue")
        }
        $shouldProcess.verbose = $true
        if ($PsItem.Path) {$Path = $_.Path}

        if ($PSCmdlet.ShouldProcess($path,"Removing OU protection from subtree")) {
            try {
                Get-ADOrganizationalUnit -server $server -searchBase $path -filter * | set-ADOrganizationalUnit -server $server -protectedFromAccidentalDeletion:$False @ShouldProcess
                write-Host "Waiting for stripped protections to fall off"
                start-sleep -seconds 3
                for ($i = 3; $i -lt $Settings.AppSettings.SleepTimeout; $i+=$Settings.AppSettings.SleepLength) {
                    $RemainingOUs = Get-ADOrganizationalUnit -server $server -searchbase $path -filter "*" -properties ProtectedFromAccidentalDeletion | where-object {$_.protectedFromAccidentalDeletion -eq $true}
                    write-Host (" OU Left: {0} (time: $i / max $Settings.AppSettings.SleepTimeout)" -f $remainingOUs.count)
                    if (-not [bool]($RemainingOUs)) {
                        write-Host " There are no protected OUs left"
                        break
                    }
                    start-sleep -seconds $Settings.AppSettings.SleepLength
                }
            } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                #we can ignore errors in getting OUs from the searchbase
                if ($_.CategoryInfo.activity -notlike "Get-*") {
                    Write-Host (" OU may have already been deleted? Error: " -f $_.Exception.InnerException)
                }
            } catch {
                $_ | fl * -force
            }
        }
        if ($PSCmdlet.ShouldProcess($path,"Deleting OU Subtree")) {
            try {
                remove-ADOrganizationalUnit -server $server -identity $path -recursive @ShouldProcess
            } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                write-loghandler -level "warning" -message " OU Subtree seeems to have already been deleted"
            }
        }
    }
}