Active Directory query script computers domain membership

Posted on 2011-05-06
Last Modified: 2012-05-11
Hello friends
i would like to ask you for your help regarding following AD query. I need a script where I will define;
- list of computers i would like to check in txt format (as source)
- let script to check if computers in source txt file are in domain or not
- write results to txt file, for each one computer in source txt file if it is or not in domain.

I dont want to touch anything else in domain so script should contain only this described query

As usual thank you very much :)
Question by:T-cko
    LVL 16

    Expert Comment

    by:Bryan Butler
    Do you want a VB script?  Powershell?  Does it matter?

    Here's a start in VB, but let us know and maybe we can give specifics.

    Powershell would be the easiest way to go.

    Author Comment

    hello developertester
    I would need to check if computers from my source file are members of domain or not and have a result about it - result like list of computers with bit saying that this or that hostname from source file is or is not in domain.
    LVL 16

    Expert Comment

    by:Bryan Butler
    Do you want a VB script?  Powershell?  Or does it matter?


    Author Comment

    Im sorry i forgot answer. i would preffer VB. thank you
    LVL 16

    Expert Comment

    by:Bryan Butler
    Hopefully someone else can help as I gotta run out.   Back next week and I'll help then if still needed.
    LVL 65

    Accepted Solution

    Hi, try this VBScript.


    Set objFSO = CreateObject("Scripting.FileSystemObject")
    strInputFile = "computers.txt"
    strOutputFile = "results.csv"
    Const intForReading = 1
    Set objInput = objFSO.OpenTextFile(strInputFile, intForReading, False)
    Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
    objOutput.WriteLine """Computer"",""In Domain?"",""adsPath"""
    While Not objInput.AtEndOfStream
    	strComputerName = Trim(objInput.ReadLine)
    	If strComputerName <> "" Then
    		strComputerADsPath = Get_LDAP_User_Properties("computer", "name", strComputerName, "adsPath")
    		If InStr(strComputerADsPath, "LDAP://") > 0 Then
    			objOutput.WriteLine """" & strComputerName & """,""Yes"",""" & strComputerADsPath & """"
                objOutput.WriteLine """" & strComputerName & """,""No"","""""
            End If
        End If
    MsgBox "Done. Please see " & strOutputFile
    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)
          ' Otherwise we just connect to the default domain
                Set objRootDSE = GetObject("LDAP://RootDSE")
                strDNSDomain = objRootDSE.Get("defaultNamingContext")
          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
          ' 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
                          strReturnVal = strReturnVal & vbCrLf & adoRecordset.Fields(intCount).Value
                    End If
              ' Move to the next record in the recordset.
          ' Clean up.
          Get_LDAP_User_Properties = strReturnVal
    End Function

    Open in new window

    LVL 67

    Expert Comment

    This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    PRTG Network Monitor: Intuitive Network Monitoring

    Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

    Companies that have implemented Microsoft’s Active Directory need to ensure that the Active Directory is configured and operating properly. If there are issues found and not resolved, it eventually leads the components to fail or stop working and fi…
    Mapping Drives using Group policy preferences Are you still using old scripts to map your network drives if so this article will show you how to get away for old scripts and move toward Group Policy Preference for mapping them. First things f…
    This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…
    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 …

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now