[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2475
  • Last Modified:

VBS Script Get Computer OU from list of Computers

Hi ,

Ok im rewriting this,
I have got a list of computers and i need to find what OU they are in , is there an easy way in VBscript to do this?

any help would be apreciated
0
Side
Asked:
Side
  • 3
  • 2
1 Solution
 
prashanthdCommented:
Try the following...but all the computers should be up and you should have privileges to query..
on error resume next

Const HKEY_LOCAL_MACHINE = &H80000002

Set cmd = CreateObject("ADODB.Command")
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.open "Provider=ADsDSOObject;"
cmd.activeconnection = cn

Set objRoot = GetObject("LDAP://RootDSE")

cmd.commandtext = "<LDAP://" & objRoot.Get("defaultNamingContext") & ">;(objectCategory=Computer);" & _
"name;subtree"
'**** Bypass 1000 record limitation ****
cmd.properties("page size")=1000

Set rs = cmd.Execute
Set objFSO = CreateObject("Scripting.FileSystemObject")

While rs.eof <> True And rs.bof <> True
    strcomputer=rs("name")
    
    Set objRegistry=GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
    
    strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon"
    
    strValueName = "DefaultUserName"
    objRegistry.GetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
    
    'WScript.Echo strValue
    
    strValueName = "DefaultDomainName"
    objRegistry.GetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
    
    WScript.Echo strcomputer &","& strValue
    
    rs.movenext
Wend

cn.close

'wscript.echo "Finished"

Open in new window

0
 
SideAuthor Commented:
Can that pull the information from a for example computers.txt file and then query AD for the particular PC name?
0
 
RobSampsonCommented:
Hi, try this.

Regards,

Rob.
Set objADSysInfo = CreateObject("ADSystemInfo")
Set objComputer = GetObject("LDAP://" & objADSysInfo.ComputerName)
MsgBox Mid(objComputer.Parent, 8)

strInputFile = "computers.txt"
strOutputFile = "results.csv"

Const intForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)
objOutputFile.WriteLine """Computer"",""OU Path"""
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)

While Not objInputFile.AtEndOfStream
	strComputerADsPath = ""
	strComputer = Trim(objInputFile.ReadLine)
	If strComputer <> "" Then
		strComputerADsPath = Get_LDAP_User_Properties("computer", "name", strComputer, "ADsPath")
		If InStr(strComputerADsPath, "LDAP://") > 0 Then
			Set objComputer = GetObject(strComputerADsPath)
			Set objComputer = GetObject("LDAP://" & objADSysInfo.ComputerName)
			strOU = Mid(objComputer.Parent, 8)
			objOutputFile.WriteLine """" & strComputer & """,""" & strOU & """"
		Else
			'Wscript.Echo "Could not find user account with email address of " & strEmail
			objOutputFile.WriteLine """" & strEmail & """,""NOT FOUND"""
		End If
	End If
Wend

objInputFile.Close
Set objInputFile = Nothing
Set objFSO = Nothing

MsgBox "Finished."

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '                        It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '                        For example, if you are searching based on the user account name, strSearchField
      '                        would be "samAccountName", and strObjectToGet would be that speicific account name,
      '                        such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '      strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '                        the home folder path, as defined by the AD, for a specific user, this would be
      '                        "homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '                        user and get your own parameters from them, then use "ADsPath" as a return string,
      '                        then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("DefaultNamingContext")
            'strDNSDomain = objRootDSE.Get("RootDomainNamingContext")
      End If

      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection

 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"

      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")

      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False

      MsgBox strQuery
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop

      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal

End Function

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
RobSampsonCommented:
Sorry, try this.

Rob.
strInputFile = "computers.txt"
strOutputFile = "results.csv"

Const intForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)
objOutputFile.WriteLine """Computer"",""OU Path"""
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)

While Not objInputFile.AtEndOfStream
	strComputerADsPath = ""
	strComputer = Trim(objInputFile.ReadLine)
	If strComputer <> "" Then
		strComputerADsPath = Get_LDAP_User_Properties("computer", "name", strComputer, "ADsPath")
		If InStr(strComputerADsPath, "LDAP://") > 0 Then
			Set objComputer = GetObject(strComputerADsPath)
			Set objComputer = GetObject("LDAP://" & objADSysInfo.ComputerName)
			strOU = Mid(objComputer.Parent, 8)
			objOutputFile.WriteLine """" & strComputer & """,""" & strOU & """"
		Else
			objOutputFile.WriteLine """" & strComputer & """,""NOT FOUND"""
		End If
	End If
Wend

objInputFile.Close
Set objInputFile = Nothing
Set objFSO = Nothing

MsgBox "Finished."

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '                        It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '                        For example, if you are searching based on the user account name, strSearchField
      '                        would be "samAccountName", and strObjectToGet would be that speicific account name,
      '                        such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '      strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '                        the home folder path, as defined by the AD, for a specific user, this would be
      '                        "homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '                        user and get your own parameters from them, then use "ADsPath" as a return string,
      '                        then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("DefaultNamingContext")
            'strDNSDomain = objRootDSE.Get("RootDomainNamingContext")
      End If

      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection

 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"

      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")

      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False

      MsgBox strQuery
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop

      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal

End Function

Open in new window

0
 
SideAuthor Commented:
Thanks that was perfect
0
 
RobSampsonCommented:
No worries. Thanks for the grade.

Rob.
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now