Delete a Computer
This guide shows you how to delete a computer in Active Directory with PowerShell.
10-15 min
Delete a Computer
Command Summary
# Delete a computer
Remove-ADComputer -Identity "PC-01" -Confirm:$false
# Delete multiple computers
Get-ADComputer -Filter {LastLogonTimeStamp -lt (Get-Date).AddDays(-90)} | Remove-ADComputer -Confirm:$false
# Delete all computers in an OU
Get-ADComputer -Filter * -SearchBase "OU=Ordinateurs,DC=lab,DC=lan" | Remove-ADComputer -Confirm:$false
Detailed Explanations
1. Delete a specific computer
To delete a single computer:
Remove-ADComputer -Identity "PC-01" -Confirm:$false
2. Delete inactive computers
To delete computers that haven't logged on in a long time:
Get-ADComputer -Filter {LastLogonTimeStamp -lt (Get-Date).AddDays(-90)} | Remove-ADComputer -Confirm:$false
3. Delete all computers in an OU
To delete all computers in an organizational unit:
Get-ADComputer -Filter * -SearchBase "OU=Ordinateurs,DC=lab,DC=lan" | Remove-ADComputer -Confirm:$false
Practical Example
Here is a complete script to clean up inactive computers:
# Définir la période d'inactivité (en jours)
$JoursInactivite = 90
# Récupérer les ordinateurs inactifs
$OrdinateursInactifs = Get-ADComputer -Filter {LastLogonTimeStamp -lt (Get-Date).AddDays(-$JoursInactivite)} -Properties LastLogonTimeStamp
# Créer un rapport des ordinateurs à supprimer
$Rapport = @()
foreach ($Ordinateur in $OrdinateursInactifs) {
$Info = [PSCustomObject]@{
Nom = $Ordinateur.Name
DernièreConnexion = $Ordinateur.LastLogonTimeStamp
JoursInactif = ((Get-Date) - $Ordinateur.LastLogonTimeStamp).Days
}
$Rapport += $Info
}