Thursday, October 15, 2020

Cleanup Windows AD delegation

Throughout the course of time, we have gone through two iterations of naming standards in regards to Hyper-V cluster node names. Since delegation is not tied to the associated computer account, the delegated server name persists within computer accounts. Meaning, when the computer account is removed, the delegation remains behind. This script will go through each, validate if the computer account actually still exists, then remove it if not. Great little way to keep things clean...

$hvObjects = Get-ADComputer -SearchBase "<ou_path>" -Filter 'Name -like "some*filter*"' -Properties msDS-AllowedToDelegateTo

foreach ($hvComputer in $hvObjects){

    Write-Verbose ('Processing computer account {0}' -f $hvComputer.Name) -Verbose

    $delegList = @()

    foreach ($deleg in ($hvComputer | Select -ExpandProperty msDS-AllowedToDelegateTo | Sort-Object)){

        $compName = (($deleg -split "/")[1] -split "\.")[0]

        if (Get-ADComputer -Filter ('Name -eq "{0}"' -f $compName) -SearchBase "<ou_path>"){
            $delegList += $deleg.ToString()
        }else{
            Write-Warning ('Computer account {0} not found, removing from delegation [{1}]' -f $compName,$deleg)            
        }

    }

    if ($delegList){
        Write-Verbose ('Setting updated delegation on computer account {0}' -f $hvComputer.Name) -Verbose
        $hvComputer| Set-ADComputer -Replace @{'msDS-AllowedToDelegateTo'= $delegList} -Verbose
    }

}

No comments:

Post a Comment