Delete Local User Accounts by OU

Posted on 2011-02-24
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"""

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
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 & """"
				objOutput.WriteLine """" & strComputer & """,""" & strGroup & """,""Error " & Err.Number & ": " & Err.Description & """"
				On Error GoTo 0
			End If
		objOutput.WriteLine """" & strComputer & """,""" & strGroup & """,""OFFLINE"""
	End If

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
		Ping = False
	End If
End Function

Open in new window

Question by:mikevr6
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 65

Accepted Solution

RobSampson earned 500 total points
ID: 34968182
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

Open in new window

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



Author Comment

ID: 34968412
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.

LVL 65

Expert Comment

ID: 34968445
Yeah, I know what that's like....tried it myself a few times....takes a while!

Let me know how it goes.


MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.


Author Closing Comment

ID: 34969012
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!!

Author Comment

ID: 34969066
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.

LVL 65

Expert Comment

ID: 34974828
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:

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.



Author Comment

ID: 34978023
Thanks again Rob!

Featured Post

More Than Just A Video Library

Train for your certification. Learn the latest DevOps tools. Grow your skillset to do better work.

At Linux Academy, we release new training modules every week so you'll always be up to date on the latest tech.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

729 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