Add/Remove User from Local Admin, based upon AD Group; User Aware

email me

This script will add or remove a domain user from the local admin group based upon their membership to an Active Directory group. You basically just drop the user into the specified group, and the script does the rest. If the user is removed from the AD group, they will be removed from the local admin group.

I tested this in the System Account, so it can be deployed using desktop management software (preferably as a regular policy), or even as part of a login script.

Things to note:

  • Was tested in W7 and W10.
  • Was tested in the system account security context.
  • Tested locally and in desktop management software.
  • If user is not logged in, the script will exit.
  • To acquire the current user from the system account, I query the explorer.exe process and return the user.
  • It does work with nested AD groups.
  • Compile this script, if used in production.

 

'I've left some simple logging in place, 
'which I used for testing in the SYSTEM ACCOUNT
'you can remove it if not needed

Option Explicit
'on error resume next

Dim objRootDSE, objDBConnection, objRecord, objList, strDomain, strADGroup, strDB
Dim StrGroupDN, strSpace, strCurrentUser, MembershipStatus, strComputer, Return
Dim strNameOfUser, ReturnedUserName, objShell, strUserDomain, colProcesses, objProcess
Set objShell = CreateObject("Wscript.Shell")


'IS USER LOGGED IN?
UserLoggedInStatus()


'AD GROUP - AD GROUP TO QUERY - GROUPS CAN BE NESTED
'SYSTEM ACCOUNT: NO ISSUES
strADGroup = "AD_Group_Name_Here"


'COMPUTERNAME
'SYSTEM ACCOUNT: NO ISSUES
'set this computer name
strComputer = objShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
strComputer = trim(strComputer)
strComputer = lcase(strComputer)


'DOMAIN OR WORKGROUP
'SYSTEM ACCOUNT: NO ISSUES
strUserDomain = objShell.ExpandEnvironmentStrings("%USERDOMAIN%")
strUserDomain = trim(strUserDomain)
strUserDomain = lcase(strUserDomain)

'used for logging - can be removed if not needed
objShell.run "cmd / md c:\setup",0,true

'WORKGROUP STATUS
'IF WORKGROUP IS FOUND, EXIT
'return in user context
if strUserDomain = strComputer then
	objShell.run "cmd /c echo user context workgroup>C:\setup\_ComputerType.txt",0,false
	Leave()
'return in SYSTEM ACCOUNT
elseif strUserDomain = "workgroup" then	
	objShell.run "cmd /c echo system account workgroup>C:\setup\_ComputerType.txt",0,false
	Leave()
elseif strUserDomain = "OtherWorkgroupName" then
	objShell.run "cmd /c echo system account workgroup>C:\setup\_ComputerType.txt",0,false
	Leave()
else
	objShell.run "cmd /c echo " & strUserDomain & ">C:\setup\_ComputerType.txt",0,false
end if



'DOMAIN
'SYSTEM ACCOUNT: NO ISSUES
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = Trim(objRootDSE.Get("DefaultNamingContext"))



'USERNAME
'SYSTEM ACCOUNT: NO ISSUES
'Returns username from explorer.exe process
GetUserName()
strCurrentUser = ReturnedUserName
strCurrentUser = trim(strCurrentUser)
strCurrentUser = lcase(strCurrentUser)
objShell.run "cmd /c echo " & strCurrentUser & ">C:\setup\_CurrentUser.txt",0,false
'some simple validation
if strCurrentUser = strComputer & "$" then Leave()
if strCurrentUser = "" then Leave()
if strCurrentUser = "system" then Leave()

'Group membership is false(disabled) by default
MembershipStatus = "False"


'SET AD DB 
strDB = "Select ADsPath From 'LDAP://" & strDomain & "' Where ObjectCategory = 'Group' AND Name = '" & strADGroup & "'"

Set objDBConnection = CreateObject("ADODB.Connection")
objDBConnection.Provider = "ADsDSOObject":	objDBConnection.Open "Active Directory Provider"
Set objRecord = CreateObject("ADODB.Recordset")

'CONNECT TO AD
objRecord.Open strDB, objDBConnection

'TEST CONNECTION
'Can't find group - exiting now
if objRecord.EOF = True then
	Leave()
end if

'SCAN THROUGH TO END OF GROUPS
'if at end, leave
If objRecord.EOF Then
	'Group not found
	on error resume next

'If not at end, access next group
Elseif Not objRecord.EOF Then	
	on error resume next	
	objRecord.MoveLast:	objRecord.MoveFirst
	While Not objRecord.EOF		
		StrGroupDN = Trim(objRecord.Fields("ADsPath").Value)
		Set objList = CreateObject("Scripting.Dictionary")
		strSpace = " "
		NestedADMembers StrGroupDN, strSpace, objList, strCurrentUser
		Set objList = Nothing		
		objRecord.MoveNext
	Wend
End If


'ONCE COMPLETE, CHECK MEMBERSHIP STATUS
If MembershipStatus = "True" then 
	AccessGranted()
Else
	RemoveAccess()
end if

'Exit
Leave()




'MY SUBs AND FUNCTIONS

'Grant admin access
Sub AccessGranted()
	on error resume next
	'SYSTEM ACCOUNT: NO ISSUES
	objShell.run "cmd /c echo GRANT ACCESS>C:\setup\_AccessStatus.txt",0,false	
	objShell.run "net localgroup administrators " & strUserDomain & "\" & strCurrentUser & " /add",0,false
	WScript.Sleep 2000	
end sub


'Remove admin access
Sub RemoveAccess()
	on error resume next
	'SYSTEM ACCOUNT: NO ISSUES
	objShell.run "cmd /c echo REMOVE ACCESS>C:\setup\_AccessStatus.txt",0,false	
	objShell.run "net localgroup administrators " & strUserDomain & "\" & strCurrentUser & " /delete",0,false
	WScript.Sleep 2000
end sub


'Exit
Sub Leave()
	on error resume next	
	objRecord.Close:	Set objRecord = Nothing
	objDBConnection.Close:	Set objDBConnection = Nothing
	Set objRootDSE = Nothing
	WScript.Sleep 5000
	WScript.Quit
end sub


'Cycles through main Group
Sub MainADGroup(ADPath, strSpace, objList, strCurrentUser)
	on error resume next
	Dim objADGroup, objADMember, strADMember
	Set objADGroup = GetObject(ADPath)	
	For Each objADMember In objADGroup.Members		
		strADMember = trim(objADMember.sAMAccountName)
		strADMember = lcase(strADMember)
		
		'SYSTEM ACCOUNT: NO ISSUES
		objShell.run "cmd /c echo " & strADMember & ">>C:\setup\_GroupMembers.txt",0,false
		
		if strADMember = strCurrentUser then
			MembershipStatus = "True"
		end if
	Next	
End Sub


'Cycle through Nested Groups
Function NestedADMembers (ADPath, strSpace, objList, strCurrentUser)
	on error resume next
	Dim objGroup, objMember, strGroupMember
	Set objGroup = GetObject(ADPath)	
	Set objShell = CreateObject("Wscript.Shell")
	
	For Each objMember In objGroup.Members		
		strGroupMember = trim(objMember.sAMAccountName)
		strGroupMember = lcase(strGroupMember)
		
		'SYSTEM ACCOUNT: NO ISSUES
		objShell.run "cmd /c echo " & strGroupMember & ">>C:\setup\_GroupMembers.txt",0,false
		
		if strGroupMember = strCurrentUser then
			MembershipStatus = "True"			
		end if
		
		If Strcomp(Trim(objMember.Class), "Group", vbTextCompare) = 0 Then
			If objList.Exists(objMember.ADsPath) Then	
				'do nothing
			Else
				objList.Add objMember.ADsPath, 1
				MainADGroup objMember.ADsPath, strSpace & " ", objList, strCurrentUser				
			End If
		End If
	Next
End Function


'Returns Username from explorer.exe
Function GetUserName()
	on error resume next
	strComputer = "." 
	Set objShell = CreateObject("Wscript.Shell")
	Set colProcesses = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery("Select * from Win32_Process Where Name = 'explorer.exe'")
	For Each objProcess in colProcesses 
		Return = objProcess.GetOwner(strNameOfUser)
		'SYSTEM ACCOUNT: NO ISSUES
		objShell.run "cmd /c echo " & strNameOfUser & ">C:\setup\_ExplorerProcessUser.txt",0,false
		If Return <> 0 Then 
			'no owner
		Else 		
			ReturnedUserName = strNameOfUser
		End If 
	Next 
End function


'Returns if user is logged on
Function UserLoggedInStatus()
	on error resume next
	Dim LoggedInStatus, objWMIService, colItems, strComputer, objshell, objItem
	Set objShell = CreateObject("Wscript.Shell")

	strComputer = "."

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

	For Each objItem in colItems
		LoggedInStatus = trim(objItem.UserName) & ""
	next

	if LoggedInStatus = "" then 
		'SYSTEM ACCOUNT: NO ISSUES
		UserLoggedInStatus = FALSE
		objShell.run "cmd /c echo " & UserLoggedInStatus & ">C:\setup\_LogonStatus.txt",0,false
		WScript.Quit(0)
	end if


	if LoggedInStatus <> "" then 
		'SYSTEM ACCOUNT: NO ISSUES
		UserLoggedInStatus = TRUE
		objShell.run "cmd /c echo " & UserLoggedInStatus & ">C:\setup\_LogonStatus.txt",0,false
	end if

	Set objItem = Nothing
	Set colItems = Nothing
	Set objWMIService = Nothing
End function