Link to home
Start Free TrialLog in
Avatar of bsharath
bsharathFlag for India

asked on

How can i update the computers location tab from the users office tab

Hi,

I want a script that can take the users "Office tab" details and update the computers location tab.
Ex:
The script has to query the notes tab where the machine name is there and update the same machine names location tab with the users Office details.

So this will help me match the users with the machine and there locations.

Regards
Sharath
Avatar of davecorun
davecorun

Avatar of RobSampson
Sharath, this is very similar to
https://www.experts-exchange.com/questions/22891046/Query-with-machine-name-and-get-location-and-username.html

Are they different in any way?

Regards,

Rob.
Avatar of bsharath

ASKER

Rob both are different...
Sharath, please try this script:

It outputs to a CSV called Computers_Updated.csv as well.

'==============
strOutputfile = "Computers_Updated.csv"

If Right(LCase(WScript.FullName), 11) = "wscript.exe" Then
      Set objShell = CreateObject("WScript.Shell")
      objShell.Run "cmd /k cscript """ & WScript.ScriptFullName & """", 1, False
      Set objShell = Nothing
      WScript.Quit
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1

strDetails = """Login Name"",""User Office"",""Computer in Notes"",""Old Computer Location"",""New Computer Location"""

Set objNetwork = CreateObject("WScript.Network")

Set colUsers = GetObject("WinNT://" & objNetwork.UserDomain)
colUsers.Filter = Array("User")

For Each objUser In colUsers
      strUserLogin = objUser.Name
      strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUserLogin, "adsPath")
      Set objUser = GetObject(strUserADsPath)
      strUserOffice = objUser.physicalDeliveryOfficeName
      strUserNotes = objUser.Info
      If strUserNotes <> "" Then
            strComputerADsPath = Get_LDAP_User_Properties("computer", "name", strUserNotes, "adsPath")
            Set objComputer = GetObject(strComputerADsPath)
            strOldComputerLocation = objComputer.Location
            objComputer.Location = strUserOffice
            objComputer.SetInfo
            WScript.Echo VbCrLf & "User Login: " & strUserLogin & VbCrLf & _
                  "User Office: " & strUserOffice & VbCrLf & _
                  "User Notes (Computer): " & strUserNotes & VbCrLf & _
                  "Old Computer Location: " & strOldComputerLocation & VbCrLf & _
                  "New Computer Location: " & objComputer.Location
            strDetails = strDetails & VbCrLf & _
                  """" & strUserLogin & """," & _
                  """" & strUserOffice & """," & _
                  """" & strUserNotes & """," & _
                  """" & strOldComputerLocation & """," & _
                  """" & objComputer.Location & """"
      End If
Next

Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)
objOutputFile.Write strDetails
objOutputFile.Close
Set objOutputFile = Nothing

WScript.Echo "Done"
MsgBox "Done"

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")
      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
                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
'==============

Regards,

Rob.
Rob i get this...

C:\>"Update Computers office tab.vbs"
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

C:\Update Computers office tab.vbs(29, 13) Microsoft VBScript runtime error: Inv
alid procedure call or argument: 'GetObject'
Above this line:
Set objComputer = GetObject(strComputerADsPath)

Please put
WScript.Echo "Computer found in Notes: " & strUserNotes
WScript.Echo "Computer ADsPath: " & strComputerADsPath

and see if you get a path returned for that computer....perhaps the name is wrong, but we should error check that I suppose....

Regards,

Rob.
I get this rob...


C:\>"Update Computers office tab.vbs"
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

Computer found in Notes: Machine Name - Dev-chen-pc2524 Computer ADsPath:
C:\Update Computers office tab.vbs(32, 13) Microsoft VBScript runtime error: Inv
alid procedure call or argument: 'GetObject'


I forgot to tell that all the users Notes has this " Machine name - " After this is the machine name.So the " Machine Name - " has to be omitted...Sorry....
Oh right, that makes sense.

Change this line:
strUserNotes = objUser.Info

to this:
strUserNotes = Trim(Replace(UCase(objUser.Info), UCase("Machine name - "), ""))

Regards,

Rob.
I get this...

User Login: AnandkumarG
User Office: HYD-3F-TR
User Notes (Computer): DEV-HYD-PC144
Old Computer Location: HYD-3F-TR
New Computer Location: HYD-3F-TR
Computer found in Notes: DEV-CHEN-PC703
Computer ADsPath: LDAP://CN=DEV-CHEN-PC703,CN=Computers,DC=Development,DC=co,DC=uk
C:\Update Computers office tab.vbs(34, 13) (null): Unspecified error

Now here what all does it do...
Hmmm, I think the Office must be empty, in which case it's trying to clear the computer location.....

Try this:

'=============
strOutputfile = "Computers_Updated.csv"

If Right(LCase(WScript.FullName), 11) = "wscript.exe" Then
      Set objShell = CreateObject("WScript.Shell")
      objShell.Run "cmd /k cscript """ & WScript.ScriptFullName & """", 1, False
      Set objShell = Nothing
      WScript.Quit
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1
Const ADS_PROPERTY_CLEAR = 1

strDetails = """Login Name"",""User Office"",""Computer in Notes"",""Old Computer Location"",""New Computer Location"""

Set objNetwork = CreateObject("WScript.Network")

Set colUsers = GetObject("WinNT://" & objNetwork.UserDomain)
colUsers.Filter = Array("User")

For Each objUser In colUsers
      If LCase(objUser.Name) = LCase("rsampson") Then
      strUserLogin = objUser.Name
      strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUserLogin, "adsPath")
      Set objUser = GetObject(strUserADsPath)
      strUserOffice = objUser.physicalDeliveryOfficeName
      strUserNotes = Trim(Replace(UCase(objUser.Info), UCase("Machine name - "), ""))
      If strUserNotes <> "" Then
            strComputerADsPath = Get_LDAP_User_Properties("computer", "name", strUserNotes, "adsPath")
            WScript.Echo "Computer found in Notes: " & strUserNotes
            WScript.Echo "Computer ADsPath: " & strComputerADsPath
            Set objComputer = GetObject(strComputerADsPath)
            strOldComputerLocation = objComputer.Location
            If strUserOffice = "" Then
                  objComputer.PutEx ADS_PROPERTY_CLEAR, "Location", 0
            Else
                  objComputer.Location = strUserOffice
            End If
            objComputer.SetInfo
            WScript.Echo VbCrLf & "User Login: " & strUserLogin & VbCrLf & _
                  "User Office: " & strUserOffice & VbCrLf & _
                  "User Notes (Computer): " & strUserNotes & VbCrLf & _
                  "Old Computer Location: " & strOldComputerLocation & VbCrLf & _
                  "New Computer Location: " & objComputer.Location
            strDetails = strDetails & VbCrLf & _
                  """" & strUserLogin & """," & _
                  """" & strUserOffice & """," & _
                  """" & strUserNotes & """," & _
                  """" & strOldComputerLocation & """," & _
                  """" & objComputer.Location & """"
      End If
      End If
Next

Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)
objOutputFile.Write strDetails
objOutputFile.Close
Set objOutputFile = Nothing

WScript.Echo "Done"
MsgBox "Done"

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")
      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
                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
'=============

Regards,

Rob.
Rob a file is created and just get a "Done" box no other error.
Right, does the file have the computer information in it?

Rob.
Its empty no data in it

Just these headers..

Login Name      User Office      Computer in Notes      Old Computer Location      New Computer Location
Oh whoops, I filtered the user list for testing....
If LCase(objUser.Name) = LCase("rsampson") Then

please comment that out, and also comment the bottom
End If

where you see this:
                  """" & objComputer.Location & """"
      End If
      End If
Next



Regards,

Rob.
I get this Rob

User Login: Clotil
User Office: SHB-GF-087
User Notes (Computer): DEV-CHEN-PC030
Old Computer Location: SHB-GF-087
New Computer Location: SHB-GF-087
Computer found in Notes: CREATED ON 18TH JULY ON THE REQUEST OF SH
Computer ADsPath:
C:\Update Computers office tab.vbs(33, 13) Microsoft VBScript runtime error: Inv
alid procedure call or argument: 'GetObject'

In this machines Notes i think there is some other details so its come out..Can this skip this


Rob i have commented this line

where you see this:
                  """" & objComputer.Location & """"
      End If
'      End If   (Is this correct)
Next


ASKER CERTIFIED SOLUTION
Avatar of RobSampson
RobSampson
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks a lot Rob this worked great
Rob just to clarify for further use of others.

First the script goes to each users queries the notes box gets the machine name.matches the machine name with the computer object then takes the Office tab data which will have the location of the user and put the same location to the Computer which it matched.
Am i right
Rob please have a look at this Q as this is useful for the same post....
It's a HTA file and i know you are the King of making them...:)

https://www.experts-exchange.com/questions/22916556/Hta-file-to-search-the-computer-and-user-in-the-specific-seat.html

Yes, that is right....