private/DeleteOUSubtreeWithConfirm.ps1
Function DeleteOUSubtreeWithConfirm { [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='high')] Param ( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [String]$path ) 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 -searchBase $path -filter * | set-ADOrganizationalUnit -protectedFromAccidentalDeletion:$False @ShouldProcess write-Host "Waiting for stripped protections to fall off" start-sleep -seconds 3 for ($i = 3; $i -lt $sleepTimeout; $i+=$sleepLength) { $RemainingOUs = Get-ADOrganizationalUnit -searchbase $path -filter "*" -properties ProtectedFromAccidentalDeletion | where-object {$_.protectedFromAccidentalDeletion -eq $true} write-Host (" OU Left: {0} (time: $i / max $sleepTimeout)" -f $remainingOUs.count) if (-not [bool]($RemainingOUs)) { write-Host " There are no protected OUs left" break } start-sleep -seconds $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 -identity $path -recursive @ShouldProcess } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { write-warning " OU Subtree seeems to have already been deleted" } } } } |