05 March 2012

Unlock AD user account with a VBscript


From time to time I need this script so I thought I would just put it somewhere handy.  Log into any domain joined machine with a user account with sufficient rights to unlock accounts.  The script will promt for the user's login name.  This would be the same as what the user uses to log in with.


******************* Start of Script ***********************

username=inputbox("Enter user logon name:")
if username = "" then wscript.quit
ldapPath = FindUser(username)
if ldapPath = "Not Found" then
wscript.echo "User not found!"
else
set objUser = getobject(ldapPath)
if isAccountLocked(objUser) then
objuser.put "lockoutTime", 0
objUser.setinfo
wscript.echo "Account Unlocked"
else
wscript.echo "This account is not locked out"
end if
end if

Function FindUser(Byval UserName)
on error resume next
set objRoot = getobject("LDAP://RootDSE")
domainName = objRoot.get("defaultNamingContext")
set cn = createobject("ADODB.Connection")
set cmd = createobject("ADODB.Command")
set rs = createobject("ADODB.Recordset")
cn.open "Provider=ADsDSOObject;"
cmd.activeconnection=cn
cmd.commandtext="SELECT ADsPath FROM 'LDAP://" & domainName & _
"' WHERE sAMAccountName = '" & UserName & "'"
set rs = cmd.execute
if err<>0 then
wscript.echo "Error connecting to Active Directory Database:" & err.description
wscript.quit
else
if not rs.BOF and not rs.EOF then
      rs.MoveFirst
      FindUser = rs(0)
else
FindUser = "Not Found"
end if
end if
cn.close
end function
******************* End of Script ***********************

No comments:

Post a Comment