public/Remove-AdComputer.ps1
function Remove-AdComputer { <# .SYNOPSIS Removes AD computer accounts by matching names to a list and searching OUs. .DESCRIPTION Provide either full OU paths with -AdOuPaths or construct paths with -AdBaseDn and -AdOuNames. .PARAMETER ComputerNames Device names to remove (usually from Intune managed devices). .PARAMETER AdOuPaths One or more full OU distinguished names to search. .PARAMETER AdBaseDn Base DN (e.g., "DC=contoso,DC=com") used with -AdOuNames. .PARAMETER AdOuNames OU names that will be combined as "OU=<name>,OU=Computers,<AdBaseDn>". .EXAMPLE Remove-AdComputer -ComputerNames $names -AdBaseDn "DC=contoso,DC=com" -AdOuNames "Clients","Admins" -WhatIf #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact='High')] param( [Parameter(Mandatory)] [string[]]$ComputerNames, [string[]]$AdOuPaths, [string]$AdBaseDn, [string[]]$AdOuNames ) if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) { throw "ActiveDirectory module not found. Install RSAT ActiveDirectory tools." } $searchBases = @() if ($AdOuPaths) { $searchBases += $AdOuPaths } elseif ($AdBaseDn -and $AdOuNames) { foreach ($n in $AdOuNames) { $searchBases += "OU=$n,OU=Computers,$AdBaseDn" } } else { throw "Provide either -AdOuPaths or both -AdBaseDn and -AdOuNames." } $adMatches = @() foreach ($sb in $searchBases) { try { $found = Get-ADComputer -Filter * -SearchBase $sb -Properties Name -ErrorAction Stop if ($found) { $adMatches += $found } } catch { Write-Warning "Failed to enumerate AD computers in '$sb'. $_" } } $targets = $adMatches | Where-Object { $_.Name -in $ComputerNames } foreach ($adc in $targets) { $label = "{0} (DN: {1})" -f $adc.Name, $adc.DistinguishedName if ($PSCmdlet.ShouldProcess("Active Directory Computer", "Remove $label")) { try { Microsoft.ActiveDirectory.Management.Commands.RemoveADComputer -Identity $adc -Confirm:$false -ErrorAction Stop Write-Verbose "Removed AD computer $label" } catch { Write-Warning "Failed to remove AD computer $label. $_" } } } } |