powershellscriptingactive-directory

Can't figure out how to delete a specific computer from AD using power shell. Can't find any solution anywhere


Most computers get deleted without a problem. But some display an error message about leaf objects.

I tried this:

Get-ADComputer -Identity "ExamplePC" | Remove-ADComputer -Server "DomainController" -Confirm:$False

Error received:

Remove-ADComputer : The directory service can perform the requested operation only on a leaf object

So after reading up on the issue, I try:

Get-ADComputer "ExamplePC" | Remove-ADObject -Recursive

and this gives me an error:

Remove-ADObject : Access is denied

FYI: I do have access to delete the computer. I'm a domain admin and if I open the Active Directory Admin Center, I can manually delete the computer without any issue. Also, most computers I run my script on don't give me any issues. Is there anything I can change or implement in my script to get past this? The "protect from accidental deletion" option is NOT enabled on the computer within AD either. I've seen this issue listed all over the place online with no resolution.


Solution

  • Perhaps this approach works, very likely the "Access Denied" exception is because you have permissions to delete the computer but the computer has leaf objects (i.e.: BitLocker) that are protected, ideally -Recursive should work but doesn't seem to be the case. Credit where credit is due, this approach is what Ansible does to workaround this error in _ADObject.psm1#L1162-L1171.

    # get the computer
    $adObject = Get-ADComputer 'ExamplePC'
    
    $adParams = @{
        # Remove below line if you don't want to target a specific DC
        Server  = 'myDC'
        Confirm = $false
    }
    
    $getADObjectSplat = @{
        Filter     = '*'
        Properties = 'ProtectedFromAccidentalDeletion'
        Searchbase = $adObject.DistinguishedName
    }
    
    # get all leaf objects for this computer
    Get-ADObject @getADObjectSplat |
        Sort-Object -Property { $_.DistinguishedName.Length } -Descending |
        ForEach-Object {
            # if the leaf object is protected
            if ($_.ProtectedFromAccidentalDeletion) {
                # set ProtectedFromAccidentalDeletion to `$false`
                $_ | Set-ADObject -ProtectedFromAccidentalDeletion $false @adParams
            }
            # remove the leaf object
            $_ | Remove-ADObject @adParams
        }
    
    # remove the computer
    $adObject | Remove-ADObject @adParams