Active Directory "pwdLastSet" Value issue

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maxamis4
    Recognized Expert Contributor
    • Jan 2007
    • 295

    Active Directory "pwdLastSet" Value issue

    Hello to start off i have a VBScript not VB. I am not sure where it goes but I figured this would be a good place to start.

    So I am querying AD to pull the Last Data an individual set their password. I have that working just fine but I have ran into a snag where not all individuals have a Last Password Set value. My code that I have to convert big integer into date handles the value which is null or to be more specific does not exist. However it returns the wrong date, I know its the wrong date because I have had individuals reset their password to confirm that its not an actual reset issue.

    I am using a standard aDODB connection into AD and this is how i am pulling the Password Set Value

    Code:
    Return Value for Password Last Set
    set objDate = adoRecordset.Fields("pwdLastSet").Value
    strPwdLastSet = Integer8Date(objDate,lngBias)
    strPwdExpDate = DateAdd("d", numDays, strPwdLastSet)
    Below is the large integer code
    Code:
    Function LargeIntegerToDate (value)
    '====================================================================================
    '
    'REFERENCES
    'http://www.selfadsi.org/ads-attributes/user-pwdLastSet.htm -doesn't handle error
    '
    '
    '
    '======================================================================================
    ' Function to convert Integer8 (64-bit) value to a date, adjusted for
        
    'takes Microsoft LargeInteger value (Integer8) and returns according the date and time
    
        'first determine the local time from the timezone bias in the registry
        Set sho = CreateObject("Wscript.Shell")
        timeShiftValue = sho.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
        
        If IsArray(timeShiftValue) Then
            timeShift = 0
            For i = 0 To UBound(timeShiftValue)
                timeShift = timeShift + (timeShiftValue(i) * 256^i)
            Next
        Else
            timeShift = timeShiftValue
        End If
    
        'get the large integer into two long values (high part and low part)
        i8High = value.HighPart
        i8Low = value.LowPart
        If (i8Low < 0) Then
               i8High = i8High + 1 
        End If
    
        'calculate the date and time: 100-nanosecond-steps since 12:00 AM, 1/1/1601
        If (i8High = 0) And (i8Low = 0) Then 
            LargeIntegerToDate = #1/1/1601#
        Else +
            LargeIntegerToDate = #1/1/1601# + (((i8High * 2^32) + i8Low)/600000000 - timeShift)/1440 
        End If
        
    End Function
    Now here is the kicker 3 days ago i had found a module that did this and actually accounted for the null value and worked. I lost it and have not been able to recover the actual value. Anyone have any suggestions.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    I'm not sure I understand, if some people don't have it set, if they change their password, then the value should now be set. And for those that are set, you say it returns the correct value. But it sounds like you're saying that the value doesn't get set even if they change their password? That sounds like an active directory issue. Or are you saying that the value is set but the code returns the wrong value?

    Comment

    • maxamis4
      Recognized Expert Contributor
      • Jan 2007
      • 295

      #3
      Rabbit,

      Thanks for your response. I am trying to figure out whether its active directory or not. I am leaning to no since i actually had a piece code about 4 days ago that handled this unknown value properly.


      Let me try to explain a bit more. I have this one user that keeps returning a value of 4/17/2014 5:68PM. Now for the sake of the discussion we will him John Williams. I personally worked with John and had him reset his password 11/4/2014. On Monday before i changed the code, John was getting February 4th as his next password change. When I made a change, which I can't totally remember what I did I started getting this 4/17/2014 date versus the actual date.

      The second part to this was my debugging session. I tried multiple times to retrieve a value from the "pwdLastSet " attritube. I continued to get an error indicating invalid object. Leverage an On Error Resume next error handling the value that is invalid is accepted and the date of 4/7/2014 is pulled out. Plus the 90 days to set the password and we have July. So i am not sure what it is about the value that is causing the error.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        So let's take a completely different approach. If what you want to do is to retrieve the date that a user last set their password and the date that they are due to change it, then I've used this code before to do that:
        Code:
        Option Explicit
        
        Dim oDomain, oUser, maxPwdAge, numDays
        Dim strUserDN, whenPasswordExpires
        
        Dim objRoot, strDomain, objConn, objComm, objRecordset
        Dim sFilter, sAttribs, sDepth, sBase, sQuery
        
        Set objRoot = GetObject("LDAP://RootDSE")
        strDomain = objRoot.Get("DefaultNamingContext")
        Set objRoot = Nothing
        Set objConn = CreateObject("ADODB.Connection")
        Set objComm = CreateObject("ADODB.Command")
        
        sFilter = "(&(objectClass=person)(sn=" & InputBox("Enter Last Name") & ")(givenName=" & InputBox("Enter First Name") & "))"
        sAttribs = "adsPath"
        sDepth = "SubTree"
        sBase = "<LDAP://" & strDomain & ">"
        sQuery = sBase & ";" & sFilter & ";" & sAttribs & ";" & sDepth
        
        objConn.Open "Data Source=Active Directory Provider;Provider=ADsDSOObject"
        Set objComm.ActiveConnection = objConn
        objComm.Properties("Page Size") = 10000
        objComm.CommandText = sQuery
        Set objRecordset = objComm.Execute
        
        Set oDomain = GetObject("LDAP://" & strDomain)
        Set maxPwdAge = oDomain.Get("maxPwdAge")
        
        ' Calculate the number of days that are held in this value.
        numDays = CCur((maxPwdAge.HighPart * 2 ^ 32) + maxPwdAge.LowPart) / CCur(-864000000000)
        'WScript.Echo "Maximum Password Age: " & numDays
        
        Set oUser = GetObject(objRecordset("adsPath"))
        whenPasswordExpires = DateAdd("d", numDays, oUser.PasswordLastChanged)
        
        'WScript.Echo "Password Last Changed: " & oUser.PasswordLastChanged
        WScript.Echo "Password Last Changed on: " & oUser.PasswordLastChanged & vbCrLf & "Password Lasts This Many Days: " & numDays & vbCrLf & "Password Expires On: " & whenPasswordExpires
        
        objConn.Close
        Set objConn = Nothing
        Set objComm = Nothing
        Set objRecordset = Nothing
        Set oUser = Nothing
        Set maxPwdAge = Nothing
        Set oDomain = Nothing

        Comment

        • maxamis4
          Recognized Expert Contributor
          • Jan 2007
          • 295

          #5
          Rabbit,

          So leveraging your code (thank you) I get the following error on record 35

          Line: 35
          Column: 1
          Error: The directory property cannot be found in the cache.

          Code: 8000500D
          Source: Active Directory

          Comment

          • maxamis4
            Recognized Expert Contributor
            • Jan 2007
            • 295

            #6
            its with a Specific user which I know has a value.

            Comment

            • Rabbit
              Recognized Expert MVP
              • Jan 2007
              • 12517

              #7
              Can you check the following:

              1) That objRecordset("a dsPath") contains a value
              2) That oUser is set to something, i.e. that it was able to retrieve a user object.

              If those things are true, then what may be happening is that your version of active directory doesn't have that property or that there is some sort of permissions issue.

              It those things aren't true, then we can try to figure out why it's not returning the correct adspath.

              Comment

              • maxamis4
                Recognized Expert Contributor
                • Jan 2007
                • 295

                #8
                Rabbit,

                Sorry to wait so long to follow up. So for every record the ADSPath does have a record. oUser for only certain users does not have a value but on error function and the values that are provided do provide a date. I know this date isn't actual since i had the users reset their accounts. Also i previously had a script that worked and a certain person that should be on this list does not show up

                I am attaching my entire code which i have scrubbed. i also have logs of the users that have wrong dates. As i mentioned in my original quote i had a different integer 8 function that had worked but I accidentally overrode it and didn't save the reference that i got the code from. When i say it worked the list of four individuals that are erroring out actually worked and i found actual people who had actually expired. Take a look and let me know what you think.

                Code:
                '=============================================================================================================================================
                '
                '		Name:		AD expiration Notification Script
                '		Author:		Our Company
                '		Date Created:	8/16/2014
                '		
                '
                '
                '		Purpose:	Script is designed to loop through Active Direcory and find
                '				all users that have password that are going to expire 
                '				and send a notification email about the expiration.
                '
                '
                '		References:
                '		http://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
                '		http://www.selfadsi.org/ads-attributes/user-pwdLastSet.htm
                '
                '==============================================================================================================================================
                
                'START SCRIPT
                
                dim errLog 'String that captures an audit of issues.
                
                Const ADS_UF_ACCOUNT_DISABLE = 2
                Const ADS_UF_HOMEDIR_REQUIRED = 8
                Const ADS_UF_LOCKOUT = 16
                Const ADS_UF_PASSWD_NOTREQD = 32
                Const ADS_UF_PASSWD_CANT_CHANGE = 64
                Const ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128
                Const ADS_UF_NORMAL_ACCOUNT = 512
                Const ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 2048
                Const ADS_UF_WORKSTATION_TRUST_ACCOUNT = 4096
                Const ADS_UF_SERVER_TRUST_ACCOUNT = 8192
                Const ADS_UF_DONT_EXPIRE_PASSWD = 65536
                Const ADS_UF_MNS_LOGON_ACCOUNT = 131072
                Const ADS_UF_SMARTCARD_REQUIRED = 262144
                Const ADS_UF_TRUSTED_FOR_DELEGATION = 524288
                Const ADS_UF_NOT_DELEGATED = 1048576
                Const ADS_UF_USE_DES_KEY_ONLY = 2097152
                Const ADS_UF_DONT_REQUIRE_PREAUTH = 4194304
                Const ADS_UF_PASSWORD_EXPIRED = 8388608
                Const ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216
                Const ADS_UF_NO_AUTH_DATA_REQUIRED = 33554432
                Const ADS_UF_PARTIAL_SECRETS_ACCOUNT = 67108864
                
                strfileName = Year(now()) & Month(now()) & Day(Now()) & Hour(now()) & minute(now()) & Second(now()) & "_ConfigLogs.txt"
                
                strfileName2 = Year(now()) & Month(now()) & Day(Now()) & Hour(now()) & minute(now()) & Second(now()) & "_UserLogs.txt"
                
                errLog = "Log start for " & now & _
                	vbcrlf & "=================================================="
                
                Audit_Log(errLog)
                
                Call LstPswdChg
                
                
                Function LstPswdChg()
                On Error Resume Next
                '==============================================================================================================================================
                '
                '		Name:  		Last Password Change Module
                '		Author:		Our Company
                '		Date Created:	8/23/2014
                '		Last Modified:	10/24/2014
                '
                '
                '		Purpose:	Find the date that the password was last changed and determine if password
                '				is going to expire.
                '
                '===============================================================================================================================================
                Const SEC_IN_DAY = 86400
                Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000
                
                
                
                	errLog = vbcrlf & "Action 01: LDAP Connection has been initiated"	
                	Audit_Log(errLog)
                    
                ' Setup ADO objects.
                Set adoCommand = CreateObject("ADODB.Command")
                Set adoConnection = CreateObject("ADODB.Connection")
                    adoConnection.Provider = "ADsDSOObject"
                    adoConnection.Open "Active Directory Provider"
                    adoCommand.ActiveConnection = adoConnection
                 
                Set objRootDSE = GetObject("LDAP://RootDSE")
                    strDNSDomain = objRootDSE.Get("defaultNamingContext")
                    strBase = "<LDAP://OU=Users,DC=Project,DC=ourcompany,DC=COM>"
                
                    'FILTER FOR LDAP
                	'===============================================================================================
                	'									TEST FILTER												   
                	'strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=juan.gomez)(!userAccountControl:1.2.840.113556.1.4.803:=2))"
                	'
                	'===============================================================================================
                	strFilter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"
                	
                	if err.number <> 0 then 
                	
                		errLog = vbcrlf & "Action 02: LDAP Filter Failed:  Error Number:" & err.number & " Error Description: " & Err.Description
                		Audit_Log(errLog)
                		Wscript.exit 
                
                	else
                
                		errLog = vbcrlf & "Action 02: LDAP Filter created " & strFilter	
                		Audit_Log(errLog)
                
                	end if 	
                
                ' Comma delimited list of attribute values to retrieve.
                    strAttr = "cn, pwdLastSet, displayName, mail, userAccountControl, distinguishedName"
                    
                    strScope = "subtree"
                    
                	errLog = vbcrlf & "Action 03: Attributes being filtered " & strAttr	
                	Audit_Log(errLog)
                
                    'ATTRIBUTES (http://www.kouti.com/tables/userattributes.htm)
                    '===========================================================
                    'SAMAccountName     CN          DistinguishedName       pwdLastSet
                    'mail               company     givenName               sn
                    'ADsPath            name        sAMAccountName          telephoneNumber
                    'initials
                    
                    'BUILD AD QUERY
                    strQuery = strBase & ";" & strFilter & ";" & strAttr & ";" & strScope
                
                	errLog = vbcrlf & "Action 04: LDAP Query " & strQuery	
                	Audit_Log(errLog)
                
                    'ADO LIMITS
                    adoCommand.CommandText = strQuery
                    adoCommand.Properties("Page Size") = 100
                    adoCommand.Properties("Timeout") = 30
                    adoCommand.Properties("Cache Results") = False
                    
                ' Run the query.
                Set adoRecordset = adoCommand.Execute
                	
                	if err.number <> 0 then 
                		errLog = vbcrlf & "Action 05: LDAP Connection Failed:  Error Number:" & err.number & " Error Description: " & Err.Description
                		Audit_Log(errLog)
                		Wscript.exit 
                	else
                		errLog = vbcrlf & "Action 05: LDAP Connection successfully Established"	
                		Audit_Log(errLog)
                	end if 
                
                Set objShell = CreateObject("Wscript.Shell")
                    
                    ' Obtain local time zone bias from machine registry.
                    lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" _
                        & "TimeZoneInformation\ActiveTimeBias") ' This bias changes with Daylight Savings Time.
                    
                    If (UCase(TypeName(lngBiasKey)) = "LONG") Then
                        lngBias = lngBiasKey
                    ElseIf (UCase(TypeName(lngBiasKey)) = "VARIANT()") Then
                        lngBias = 0
                        For k = 0 To UBound(lngBiasKey)
                            lngBias = lngBias + (lngBiasKey(k) * 256 ^ k)
                        Next
                    End If
                
                	errLog = vbcrlf & "Action 06: Daylight savings adjustment time is " & lngbias	
                	Audit_Log(errLog)
                
                'OBTAIN DC PASSWORD AGE POLICY
                Set oDomain = GetObject("LDAP://DC=Users,DC=ourcompany,DC=COM")
                Set maxPwdAge = oDomain.Get("maxPwdAge")
                     
                    numDays = CCur((maxPwdAge.HighPart * 2 ^ 32) + maxPwdAge.LowPart) / CCur(-864000000000)
                
                	errLog = vbcrlf & "Action 07: Password Policy verified as " & numDays & " expiration time"	
                	Audit_Log(errLog)
                	
                        
                    'LOOP THROUGH RECORDS
                	errLog = "CN,Email,LstPwdSet,PwdExpDate,DaystoExp,expFlg,emailFlg,UserDisabled"	
                	User_Log(errLog)
                	
                	if err.number <> 0 then 
                		errLog = vbcrlf & "Action 08: User Log file creation failed:  Error Number:" & err.number & " Error Description: " & Err.Description
                		Audit_Log(errLog)
                		Wscript.quit
                	else
                		errLog = vbcrlf & "Action 08: User Log file created!"
                		Audit_Log(errLog)
                	end if
                
                    Do While Not adoRecordset.EOF
                		' Retrieve values and display.
                            strUserName = adoRecordset.Fields("DisplayName").Value
                            
                            strEmail = adoRecordset.Fields("mail").Value
                            
                            strDN = adoRecordset.Fields("distinguishedName").Value
                            
                            If strEmail = "Problem.users@ourcompany.com Then
                            
                            	strtest = "Stop Value"
                            
                            End If 
                            
                            strCN = adoRecordset.Fields("cn").Value
                            
                            If strCN = "DB2 Admin" Then
                            	strtest = "Stop Value"
                            End If 
                			
                		'Return Value for Password Last Set
                			set objDate = adoRecordset.Fields("pwdLastSet").Value
                			strPwdLastSet = Integer8Date(objDate, lngBias)
                			strPwdExpDate = DateAdd("d", numDays, strPwdLastSet)
                
                		 'Code 66048 means Password never expires  http://technet.microsoft.com/en-us/library/ee198831.aspx
                		 'http://www.netvision.com/ad_useraccountcontrol.php
                			strFlgPwdExp = adoRecordset.Fields("userAccountControl").Value
                			
                			'If flag doesn't have attributes and has no email it must be a service account.  Set flag to do not expire for script.
                			if isnull(strFlgPwdExp) Then
                				if  isnull(strEmail) Then
                				
                					strFlgPwdExp = 66048
                					
                				else
                					'Give flag value a value to meet condition 512 Active account
                					strFlgPwdExp = 512
                				
                				end if 
                		
                			end if
                			
                			err.clear
                			
                			strDisabled = false 'General Flag is set to indicate that accounts do not need to be disabled.
                			
                			pwddaysleft = datediff("d",now(),strPwdExpDate)
                            
                				if err.number <> 0 then 
                					errLog = vbcrlf & "Action 09: Field declaration error:" & err.number & " Error Description: " & Err.Description & "-" & strusername
                					Audit_Log(errLog)
                					Wscript.quit 
                				else
                					errLog = vbcrlf & "Action: Field declaration successfully " & Now()
                					Audit_Log(errLog)
                				end if
                			
                            If strFlgPwdExp = 66048 Then  
                				emailFlg = false
                            Else            
                				
                				If pwddaysleft < 15 Then
                
                					strToEmail = strEmail
                                    
                                	strFromEmail = "ops@ourcompayn.com"
                    
                                    strSubject = "Company SECURITY AUTO GENERATED EMAIL:  Password Expiration Notification"
                                	
                					if isnull(strToEmail) = False Then	 	                 
                						emailFlg = true 'This creates a value for the email flag which indicates that there is an email.
                	
                						if pwddaysleft > 0  Then
                								PswdMsg = "Your password will expire on " & strPwdExpDate & ".  You have " & pwddaysleft & " days left to change your password before you are locked out of the system.  Please Login to Server <b> 10.3.2.104 </b> to change your password.  "
                						Else
                								PswdMsg = "Your password expired on " & strPwdExpDate & ".  You have 30 days from the date of expiration to contact your administrator before your account is disabled.  "
                								
                								if pwddaysleft >-31   Then
                									strDisabled = "True"
                								End if
                						end if
                	
                						strMessage = "<HTML>"
                						strMessage = strMessage & "<HEAD>"
                						strMessage = strMessage & "<BODY>"
                						strMessage = strMessage & "Password Change required"
                						strMessage = strMessage & "<br>"
                						strMessage = strMessage & strCN & ","
                						strMessage = strMessage & "<br>"
                						strMessage = strMessage & "<br>"
                						strMessage = strMessage & PswdMsg
                						strMessage = strMessage & "You will continue to receive this message daily until you have successfully updated your password.  Please contact our system administrator for issues or concerns."
                						strMessage = strMessage & "<br><br>"
                						strMessage = strMessage & "Please contact IT Operations at sysadmin@ourcompany.com for questions or support issues."
                						strMessage = strMessage & "<br><br>"
                						strMessage = strMessage & "</BODY>"
                						strMessage = strMessage & "</HTML>"	
                
                						'==============>  Add apostrophe to stop emails '
                			
                						Call SendEmail(strToEmail, strFromEmail, strSubject, strMessage) 
                						
                						strUserList = strUserList & "<tr>"
                						strUserList = strUserList & "<td>" & strCN & "</td>"
                						strUserList = strUserList & "<td>" & strPwdExpDate & "</td>"
                						strUserList = strUserList & "</tr>"
                					
                					else
                						emailFlg = False
                						strUserEmail = strUserEmail & "<tr>"
                						strUserEmail = strUserEmail & "<td>" & strCN & "</td>"
                						strUserEmail = strUserEmail & "<td>" & emailFlg & "</td>"
                						strUserEmail = strUserEmail & "</tr>"
                					
                					End if  
                
                                End If
                                
                            End If
                			
                		errLog = strCN & "," & strEmail & "," & strPwdLastSet & "," & strPwdExpDate & "," & pwddaysleft & "," & strFlgPwdExp & "," & emailFlg & "," & strDisabled
                		User_Log(errLog) 
                
                		if err.number <> 0 then 
                			errLog = vbcrlf & "Action 12: User Log file input error:" & err.number & " Error Description: " & Err.Description
                			Audit_Log(errLog)
                			Wscript.quit 
                		else
                			errLog = vbcrlf & "Action: User Log file input successful " & now()
                			Audit_Log(errLog)
                		end if  
                							
                		adoRecordset.MoveNext
                        
                    Loop
                
                		if isnull(strUserlist) then
                			strUserList = "No Password Expirations for " & now()
                		end if 
                		
                		striTopsEmail = striTopsEmail & "<HTML>"
                		striTopsEmail = striTopsEmail & "<HEAD>"
                		striTopsEmail = striTopsEmail & "<style>"
                		striTopsEmail = striTopsEmail & "table, th, td {border: 1px solid black;border-collapse: collapse;}"
                		striTopsEmail = striTopsEmail & "th, td {padding: 5px;text-align: left;}"
                		striTopsEmail = striTopsEmail & "</style>"
                		striTopsEmail = striTopsEmail & "</head>"
                		striTopsEmail = striTopsEmail & "<BODY>"
                		striTopsEmail = striTopsEmail & "DAILY USER PASSWORD SUMMARY For " & now()
                		striTopsEmail = striTopsEmail & "<br>"
                		striTopsEmail = striTopsEmail & "<table border='1' style='width:100%'>"
                		striTopsEmail = striTopsEmail & "<tr>"
                		striTopsEmail = striTopsEmail & "<th bgcolor='#BDBDBD'>User Name </th>"
                		striTopsEmail = striTopsEmail & "<th bgcolor='#BDBDBD'>Expiration Day </th>"
                		striTopsEmail = striTopsEmail & strUserList
                		striTopsEmail = striTopsEmail & "</table>"
                		striTopsEmail = striTopsEmail & "<br><br><br>"
                		striTopsEmail = striTopsEmail & "DAILY USER EMAIL SUMMARY For " & now()
                		striTopsEmail = striTopsEmail & "<br>"
                		striTopsEmail = striTopsEmail & "<table border='1' style='width:100%'>"
                		striTopsEmail = striTopsEmail & "<tr>"
                		striTopsEmail = striTopsEmail & "<th bgcolor='#BDBDBD'>User Name </th>"
                		striTopsEmail = striTopsEmail & "<th bgcolor='#BDBDBD'>HAS EMAIL </th>"
                		striTopsEmail = striTopsEmail & strUserEmail
                		striTopsEmail = striTopsEmail & "</table>"
                		
                		
                		strToEmail = "ops@ourcompany.com"
                		strFromEmail = "sysadmin@ourcompany.com"
                		strSubject = "DAILY USER PASSWORD SUMMARY"
                		
                		Call SendEmail(strToEmail, strFromEmail, strSubject, striTopsEmail) 
                
                		if err.number <> 0 then 
                			errLog = vbcrlf & "Action 13: Daily User Report error:" & err.number & " Error Description: " & Err.Description
                			Audit_Log(errLog)
                			Wscript.quit 
                		else
                			errLog = vbcrlf & "Action 13: Daily email sent to IT Admins at " & now()
                			Audit_Log(errLog)
                		end if  	
                
                adoRecordset.Close
                adoConnection.Close
                
                
                Set oUser = Nothing
                Set maxPwdAge = Nothing
                Set oDomain = Nothing
                		
                End function
                
                
                
                function SendEmail(strToEmail, strFromEmail, strSubject, strMessage)
                '==============================================================================================================================================
                '
                '		Name:  		Send email
                '		Author:		Our Company
                '		Date Created:	8/23/2014
                '		Last Modified:	10/23/2014
                '
                '
                '		Purpose:	Send an email based on the attributes passed into the module
                '				
                '
                '===============================================================================================================================================
                
                
                	Set iMsg = CreateObject("CDO.Message")
                	Set iConf = CreateObject("CDO.Configuration")
                	Set Flds = iConf.Fields
                	
                	schema = "http://schemas.microsoft.com/cdo/configuration/"
                
                	Flds.Item(schema & "sendusing") = 2
                	Flds.Item(schema & "smtpserver") = "email-smtp.ourcompany.com"
                	Flds.Item(schema & "smtpserverport") = 465
                	Flds.Item(schema & "smtpauthenticate") = 1
                	Flds.Item(schema & "sendusername") = "customer user"
                	Flds.Item(schema & "sendpassword") = "password set"
                	Flds.Item(schema & "smtpusessl") = 1
                	Flds.Update
                
                	if err.number <> 0 then 
                		errLog = vbcrlf & "Action 11: SMTP bind error:" & err.number & " Error Description: " & Err.Description & "-" & strToEmail
                		Audit_Log(errLog)
                		Wscript.quit 
                	Else
                		errLog = vbcrlf & "Action: SMTP bind successful " & Now()
                		Audit_Log(errLog)
                	End if 
                	
                	With iMsg
                		
                		.To = "testuser@ourcompany.com"
                		'To = strToEmail
                		.From = strFromEmail
                		.Subject = strSubject
                		.HTMLBody = strMessage	
                		.Sender = " "
                		.Organization = "OUR Company"
                		.ReplyTo = "sysadmin@ourcompany.com"
                		
                		Set .Configuration = iConf
                		SendEmail = .Send
                
                	End With
                	
                	if err.number <> 0 then 
                		errLog = vbcrlf & "Action 11: SMTP send error:" & err.number & " Error Description: " & Err.Description & "-" & strToEmail
                		Audit_Log(errLog)
                		Wscript.quit 
                	Else
                		errLog = vbcrlf & "Action: " & Now() & " Email sent successfully to " & strToEmail
                		Audit_Log(errLog)
                	End if 
                
                	set iMsg = nothing
                	set iConf = nothing
                	set Flds = nothing
                
                End function
                
                Function Audit_Log(strlogfile)
                
                	Const ForReading = 1, ForWriting = 2, ForAppending = 8 
                	strPath = "C:\scripts\Logs\"
                
                	Set fso = CreateObject("Scripting.FileSystemObject")
                	Set oFile = FSO.OpenTextFile(strPath & strfileName, ForAppending, True)
                
                	oFile.WriteLine strlogfile
                	oFile.Close
                
                	Set fso = Nothing
                	Set oFile = Nothing 
                	
                end Function
                
                Function User_Log(strlogfile)
                
                	Const ForReading = 1, ForWriting = 2, ForAppending = 8 
                	strPath = "C:\scripts\Logs\"
                
                	Set fso = CreateObject("Scripting.FileSystemObject")
                	Set oFile = FSO.OpenTextFile(strPath & strfileName2, ForAppending, True)
                
                	oFile.WriteLine strlogfile
                	oFile.Close
                
                	Set fso = Nothing
                	Set oFile = Nothing 
                	
                end Function
                
                Function Integer8Date(ByVal objDate, ByVal lngBias)
                    ' Function to convert Integer8 (64-bit) value to a date, adjusted for
                    ' local time zone bias.
                    Dim lngAdjust, lngDate, lngHigh, lngLow
                    lngAdjust = lngBias
                    lngHigh = objDate.HighPart
                    lngLow = objDate.LowPart
                    ' Account for error in IADsLargeInteger property methods.
                    If (lngLow < 0) Then
                        lngHigh = lngHigh + 1
                    End If
                    If (lngHigh = 0) And (lngLow = 0) Then
                        lngAdjust = 0
                    End If
                    lngDate = #1/1/1601# + (((lngHigh * (2 ^ 32)) _
                        + lngLow) / 600000000 - lngAdjust) / 1440
                    ' Trap error if lngDate is ridiculously huge.
                    On Error Resume Next
                    Integer8Date = CDate(lngDate)
                    If (Err.Number <> 0) Then
                        On Error GoTo 0
                        Integer8Date = #1/1/1601#
                    End If
                    On Error GoTo 0
                
                End Function

                Comment

                • Rabbit
                  Recognized Expert MVP
                  • Jan 2007
                  • 12517

                  #9
                  I'm out of the office for a few days so I don't have any domain to test against. I'll have to get back to you on this later this week.

                  Comment

                  • Rabbit
                    Recognized Expert MVP
                    • Jan 2007
                    • 12517

                    #10
                    In your code, I don't see where you return the adsPath in the query you run and I don't see where you use the adsPath that is returned to get the user object. Which is line 34 in my code on post #4.

                    Comment

                    • maxamis4
                      Recognized Expert Contributor
                      • Jan 2007
                      • 295

                      #11
                      So closing the loop here on this problem. Script is perfect, (as it is in the eye of the beholder) and it seems the only issue i was having was not running the script as an administrator. Image that, i was running the script as my self (who is an admin) but not elevating it at the system. Miss the good old days of windows.

                      Cheers.

                      Comment

                      • Rabbit
                        Recognized Expert MVP
                        • Jan 2007
                        • 12517

                        #12
                        Glad you got the issue sorted out. We must have different group policies, I don't need to elevate the script to run it.

                        Comment

                        Working...