Find the location of a computer account in Active Directory

From Wiki

Jump to:navigation, search

Creator: IT Support Staff @ HCHS

Script Language: VBS

Forum topic Link:

This script will find and display the exact location of a computer user account in Active Directory.

<vb>OPTION EXPLICIT DIM objNetwork DIM computerName DIM ou

' Get the computerName of PC set objNetwork = createobject("Wscript.Network") 'computerName = objNetwork.ComputerName computername = Inputbox("Enter the network name of the PC to find :")

' Call function to find OU from computer name ou = getOUByComputerName(computerName)

IF ou = "" THEN ou = "Not Found"

wscript.echo ou

function getOUByComputerName(byval computerName) ' *** Function to find ou/container of computer object from computer name ***

DIM namingContext, ldapFilter, ou DIM cn, cmd, rs DIM objRootDSE

' Bind to the RootDSE to get the default naming context for ' the domain. e.g. dc=HCHS,dc=co,dc=uk set objRootDSE = getobject("LDAP://RootDSE") namingContext = objRootDSE.Get("defaultNamingContext") set objRootDSE = nothing

' Construct an ldap filter to search for a computer object ' anywhere in the domain with a name of the value specified. ldapFilter = "<LDAP://" & namingContext & _

	">;(&(objectCategory=Computer)(name=" & computerName & "))" & _


' Standard ADO code to query database set cn = createobject("ADODB.Connection") set cmd = createobject("ADODB.Command") "Provider=ADsDSOObject;" cmd.activeconnection = cn cmd.commandtext = ldapFilter

set rs = cmd.execute

if rs.eof <> true and rs.bof <> true then ou = rs(0) ' Convert distinguished name into OU. ' e.g. cn=CLIENT01,OU=HCHS_Computers,dc=HCHS,dc=co,dc=uk ' to: OU=HCHS_Computers,dc=HCHS,dc=co,dc=uk ou = mid(ou,instr(ou,",")+1,len(ou)-instr(ou,",")) getOUByComputerName = ou

end if

rs.close cn.close

end function</vb>