Solved

Delete Local User Accounts by OU

Posted on 2011-02-24
7
704 Views
Last Modified: 2012-08-13
Good Day,

After performing an audit on all our Workstations. I have discovered some Local Administrator accounts which do not follow our normal build standard naming convention. There are around 150 workstations with this misconfiguration. I would like to script their deletion (the proper Admin account also exists on these machines, renamed correctly via GPO). Can someone help me with the script please. It should read the machine names in from an OU in Active Directory, connect to each machine and delete the 2 rogue accounts if they exist.

I already have some code, thanks to a previous post, which reads in machine names from AD and outputs a list of Local Group members to a .csv file. Please see below.

rrGroups = Array("Administrators", "Remote Desktop Users", "Users")
strOutput = "LocalGroupMembers.csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutput = objFSO.CreateTextFile(strOutput, True)
objOutput.WriteLine """COMPUTER"",""GROUP NAME"",""MEMBER NAME"""

Const ADS_SCOPE_SUBTREE = -2 
 
Set oConn = CreateObject("ADODB.Connection") 
Set oCommand = CreateObject("ADODB.Command") 
oConn.Provider = "ADsDSOObject" 
oConn.Open "Active Directory Provider" 
Set oCommand.ActiveConnection = oConn 
 
oCommand.Properties("Page Size") = 1000 
oCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
 
sOU = "'LDAP://OU=ouServers,DC=example,DC=com'"

oCommand.CommandText = "SELECT Name, ADsPath FROM " & sOU & " WHERE objectCategory ='computer'" 
Set oRecordSet = oCommand.Execute
oRecordSet.MoveFirst
Do Until oRecordSet.EOF
	strComputer = oRecordSet.Fields("Name").Value
	If Ping(strComputer) = True Then
		For Each strGroup In arrGroups
			'WScript.Echo "List of member of local Administrators group for " & strComputer
			On Error Resume Next
			Set oLocalAdmins = GetObject("WinNT://" & strComputer & "/" & strGroup) 
			If Err.Number = 0 Then
				On Error GoTo 0
				For Each oLocalAdmin in oLocalAdmins.Members 
					objOutput.WriteLine """" & strComputer & """,""" & strGroup & """,""" & oLocalAdmin.Name & """"
				Next
			Else
				objOutput.WriteLine """" & strComputer & """,""" & strGroup & """,""Error " & Err.Number & ": " & Err.Description & """"
				Err.Clear
				On Error GoTo 0
			End If
		Next
	Else
		objOutput.WriteLine """" & strComputer & """,""" & strGroup & """,""OFFLINE"""
	End If
	oRecordSet.MoveNext
Loop
objOutput.Close

MsgBox "Done. Please see " & strOutput

Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function

Open in new window

0
Comment
Question by:mikevr6
  • 4
  • 3
7 Comments
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
Comment Utility
Hi, if you actually know the name of the accounts you want to delete, the easiest way to get rid of them would be to add a StartUp script from a GPO, with the following code in it:

 
On Error Resume Next
Set objNetwork = CreateObject("WScript.Network")
arrUsers = Array("AdminWrong", "RDWrong")
Set objComputer = GetObject("WinNT://" & objNetwork.ComputerName & "")
For Each strUser In arrUsers
   objComputer.Delete "user", strUser
Next

Open in new window


That way, the accounts are deleted by the local SYSTEM account, and if they don't exist, nothing happens.

Regards,

Rob.
0
 

Author Comment

by:mikevr6
Comment Utility
Hi Rob,

That is much better. It will catch every machine as it logs on. Rather than me running a script multiple times trying to catch machines while they're online and still missing a few.

I'll give it a test and post back the results.

Mike
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Yeah, I know what that's like....tried it myself a few times....takes a while!

Let me know how it goes.

Regards,

Rob.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Closing Comment

by:mikevr6
Comment Utility
Works great! No modification required. (other than inserting the usernames of course) ;)
And copy the script to the Netlogon or Sysvol share so it's available to all machines.

Merci Buckets!!
0
 

Author Comment

by:mikevr6
Comment Utility
One question. My Manager is sure to ask.

If we want to do the reverse, delete all user accounts NOT defined in arrUsers. Can you show me the code for this please.

Thanks
Mike
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Hi, that get's slightly more complicated because you need to enumerate each group for their members, and if the user is not in the array, then delete them.

One way, however, that would cover both scenarios at once, is to use Group Policy Restricted Groups:
http://www.frickelsoft.net/blog/?p=13

This ensures that certian local groups have only the specified members, but it doesn't *delete* the accounts....if you do want to delete the accounts, I can knock up the other version for you.

Regards,

Rob.
0
 

Author Comment

by:mikevr6
Comment Utility
Thanks again Rob!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

[b]Ok so now I will show you how to add a user name to the description at login. [/b] First connect to your DC (Domain Controller / Active Directory Server) SET PERMISSIONS FOR SCRIPT TO UPDATE COMPUTER DESCRIPTION TO USERNAME 1. Open Active …
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now