Solved

Exchange forward code need help

Posted on 2011-09-13
13
290 Views
Last Modified: 2012-05-12
Hi,

Exchange forward code need help
Code from Rob works great but need the forward checkbox selected as it sets the forward

Can anyone help Forward
'=======================
strInputFile = "EmailForwards.txt"

Const intForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)

While Not objInputFile.AtEndOfStream
      strIntUserADsPath = ""
      strExtUserDN = ""
      arrAddresses = Split(objInputFile.ReadLine, ";")
      strInternalEmail = arrAddresses(0)
      strExternalEmail = arrAddresses(1)
      strIntUserADsPath = Get_LDAP_User_Properties("user", "mail", strInternalEmail, "ADsPath")
      If InStr(strIntUserADsPath, "LDAP://") > 0 Then
            strExtUserADsPath = Get_LDAP_User_Properties("contact", "mail", strExternalEmail, "ADsPath")
            If InStr(strExtUserADsPath, "LDAP://") > 0 Then
                  Set objIntUser = GetObject(strIntUserADsPath)
                   'objIntUser.Put "AltRecipient", Replace(strExtUserDN, "LDAP://", "")
                  ' OR MAYBE ALSO
                  objIntUser.Put "AltRecipient", Replace(strExtUserADsPath, "LDAP://", "")

                 objIntUser.SetInfo
            Else
                  MsgBox "Could not find an external contact with an email address of " & strExternalMail
            End If
      Else
            MsgBox "Could not find an internal user account with an email address of " & strInternalEmail
      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
Comment
Question by:bsharath
  • 8
  • 5
13 Comments
 
LVL 65

Expert Comment

by:RobSampson
ID: 36533772
Hi Sharath,

Try changing this:
                 objIntUser.SetInfo

To this:
                 objIntUser.deliverAndRedirect = True
                 objIntUser.SetInfo

Regards,

Rob.
0
 
LVL 11

Author Comment

by:bsharath
ID: 36533891
Perfect thanks Rob
One more addition
After setting this i want the Contact moved to another OU
Also now i get popup's need to disable that and get success and failure report
0
 
LVL 11

Author Comment

by:bsharath
ID: 36533961
Hi Rob any help...
Need to do few 1,000 now.. :-)
0
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
LVL 65

Expert Comment

by:RobSampson
ID: 36533978
OK, try this.  If you don't want the last "Finished" message, just comment it out.

Regards,

Rob.
'=======================
strInputFile = "EmailForwards.txt"
strNewOU = "OU=NewContacts,DC=Domain,DC=Com"
strLogFile = "EmailForwardsLog.txt"

Const intForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
Set objOU = GetObject("LDAP://" & strNewOU)

Set objLog = objFSO.CreateTextFile(strLogFile, True)
objLog.WriteLine "Emails forwards script running " & Now
objLog.WriteLine "Moving accounts to " & strNewOU & vbCrLf

While Not objInputFile.AtEndOfStream
	strIntUserADsPath = ""
	strExtUserDN = ""
	arrAddresses = Split(objInputFile.ReadLine, ";")
	strInternalEmail = arrAddresses(0)
	strExternalEmail = arrAddresses(1)
	strIntUserADsPath = Get_LDAP_User_Properties("user", "mail", strInternalEmail, "ADsPath")
	If InStr(strIntUserADsPath, "LDAP://") > 0 Then
		strExtUserADsPath = Get_LDAP_User_Properties("contact", "mail", strExternalEmail, "ADsPath")
		If InStr(strExtUserADsPath, "LDAP://") > 0 Then
			Set objIntUser = GetObject(strIntUserADsPath)
			'objIntUser.Put "AltRecipient", Replace(strExtUserDN, "LDAP://", "")
			' OR MAYBE ALSO
			objIntUser.Put "AltRecipient", Replace(strExtUserADsPath, "LDAP://", "")
			objIntUser.deliverAndRedirect = True
			On Error Resume Next
			objIntUser.SetInfo
			If Err.Number = 0 Then
				objLog.WriteLine "Successfully set attributes for " & objIntUser.DisplayName
				intReturn = objOU.MoveHere(strADsPath, vbNullString)
				If intReturn = 0 Then
					objLog.WriteLine objIntUser & " moved to " & strNewOU
				Else
					objLog.WriteLine "Failed to move " & objIntUser & " to " & strNewOU
				End If
			Else
				objLog.WriteLine "Failed to set attributes for " & objIntUser.DisplayName & ". Error " & Err.Number & ": " & Err.Description
			End If
			Err.Clear
			On Error Goto 0
		Else
			'MsgBox "Could not find an external contact with an email address of " & strExternalMail
			objLog.WriteLine "Could not find an external contact with an email address of " & strExternalMail
		End If
	Else
		'MsgBox "Could not find an internal user account with an email address of " & strInternalEmail
		objLog.WriteLine "Could not find an internal user account with an email address of " & strInternalEmail
	End If
Wend

objInputFile.Close
objLog.Close
Set objInputFile = Nothing
Set objFSO = Nothing

WScript.Echo "Finished. Please see " & strLogFile

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
 
LVL 11

Author Comment

by:bsharath
ID: 36534344
Rob i get this


---------------------------
Windows Script Host
---------------------------
Script:      D:\Set Forwards.vbs
Line:      22
Char:      2
Error:      Subscript out of range: '[number: 1]'
Code:      800A0009
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------

Also i still get the msg boxes and does not move to the new OU
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 36534965
That's a very odd error to have at that point......is the data in the file valid?

I think it might be this line that has the error:
      strExternalEmail = arrAddresses(1)

which suggests there's a line in the file without the semi-colon and an external email address.

Rob.
0
 
LVL 11

Author Comment

by:bsharath
ID: 36535011
Thanks Rob it works. Now just the move does not work
0
 
LVL 11

Author Comment

by:bsharath
ID: 36535160
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 36535187
Oh, change
                        intReturn = objOU.MoveHere(strADsPath, vbNullString)
to
                        intReturn = objOU.MoveHere(strIntUserADsPath, vbNullString)

Rob.
0
 
LVL 11

Author Comment

by:bsharath
ID: 36535197
Rob i think this is moving users i want the contacts moved
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
ID: 36535294
Oh, is that this then?

                        intReturn = objOU.MoveHere(strExtUserADsPath, vbNullString)

Rob.
0
 
LVL 11

Author Comment

by:bsharath
ID: 36540457
0
 
LVL 11

Author Comment

by:bsharath
ID: 36565343
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Clear Filter 8 61
Creating An Intelligent Dropdown, Part Deux! 9 32
Connecting The Dots from Range Value to Listbox ListIndex 11 24
IDE for Python 5 25
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

830 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