V
V
v00deg2015-06-04 10:59:58
PowerShell
v00deg, 2015-06-04 10:59:58

How to automate the deletion of objects in AD?

Good afternoon!
I'm trying to automate the cleaning of AD from the computers of laid-off employees, here is an example of a script:

$DisableUsers = Get-ADUser -Filter 'Enabled -eq "False"' -SearchBase 'OU=2,OU=1,DC=company,DC=name'

foreach ($User in $DisableUsers){$Name = $User.samaccountname}

Get-ADComputer -Identity "$Name"  | Remove-ADComputer -ErrorAction SilentlyContinue -confirm:$false

As a result, I get the following:
Get-ADComputer : Cannot find an object with identity: 'computername' under: 'DC=company,DC=name'.
At line:1 char:1
+ Get-ADComputer -Identity "$Name"  | Remove-ADComputer -ErrorAction SilentlyConti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (computername:ADComputer) [Get-ADComputer], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetAD 
   Computer

Although such an object is available, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene, 2015-06-04
@yellowmew

Do you have a user's computer called completely the same as the user's name?
Strange decision.
In general, in AD, computers and users are two different, independent objects.
You can put a new user on the computer of a fired user, and recreating a computer from scratch for each new employee, including adding it to the domain, is ... strange.
It is more correct to disable inactive computer records that have not been part of the domain for a long time.
But in general, to help you:
community.spiceworks.com/scripts/show/1861-find-an...

N
Nikolai, 2015-06-04
@hellsq

print out the values ​​of $Name. It may well turn out that it will not be quite what you expected. Plus, I don't quite understand why it was necessary to put $Name in quotes when calling Get-Adcomputer.

D
Denis Kolmykov, 2015-06-07
@dinizzzo

Do you have a computer name in AD that matches the SamAccountname of the same computer? Those. a situation is possible when a computer in AD is called, for example: "Vasya's computer", and itself has the name "[email protected]". So in this case, the computer name parameter will be "Vasya's Computer", and SamAccountname "wks0001$" (with a $ sign at the end), and then the Get-ADComputer -Identity "wks0001" command will not work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question