Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to tell if script ran successfully

Status
Not open for further replies.

gmagerr

Technical User
Aug 11, 2001
323
US
Hi All

I have a password notification script I'm running nightly. I have a section that sends out an email to the users, and one that sends an email to the sysadmins telling them the script ran successfully. When the script runs, it creates a text file called userpwd.txt The way I'm determining a successful or failed run is not working. I'm getting the date modified of the newly created file and comparing it to the Now() if the date modofoed of the file doesn't match Now() then I'm saying the script didn't run. Is there a better more accurate way to do this? Here's the code.

Thanks

Code:
'==========================================================================
' 
' NAME: Password Notification
' 
' AUTHOR: Gene Magerr
' EMAIL: genemagerr@hotmail.com
'
' COMMENT: Original Script by [URL unfurl="true"]www.d2ww.com[/URL] Modified by Gene Magerr
'
' VERSION HISTORY:
' 1.0   10/03/2007  Initial release
'
'==========================================================================
Option Explicit

'==========================================================================
' If TestMode is set to true, all wscript.echo messages will be displayed,
' if set to False no messages are displayed
'==========================================================================
TestMode = False

'==========================================================================
' VARIABLE DECLARATIONS
'==========================================================================
Dim objCommand, objConnection, strBase, objFSO, TestMode, objFile, strFilter
Dim strAttributes, strPasswordChangeDate, intPassAge, lngTZBias, objPwdLastSet
Dim strEmailAddress, objShell, lngBiasKey, k, PasswordExpiry, strRootDomain     
Dim strQuery, objRecordset, strName, strCN, strNoOfDays, strPWChangeDate
Dim strChangeDate, strPasswordExpiry, strEmployeeID, strLoginName
Dim CalcDate, objMessage, eCounter, intExpiresIn, objEmail
Dim strFile, strStatus, strNow, file, strFileDate, strDestEmail

'==========================================================================
' STATIC VARIABLE ASSIGNMENTS
'==========================================================================
Const FOR_READING = 1, FOR_WRITING = 2, FOR_APPENDING = 8

'==========================================================================
' MAIN SCRIPT CODE
'==========================================================================
'If TestMode = True Then
'WScript.Echo "Put Message Here"
'End If

'==========================================================================
' Set the password expiration time and the domain
'==========================================================================
PasswordExpiry = 90
strRootDomain = "dc=mycompany,dc=org"

'==========================================================================
' Get the Active time on the Server
'==========================================================================
Set objShell = CreateObject("Wscript.Shell")
lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
If UCase(TypeName(lngBiasKey)) = "LONG" Then
    lngTZBias = lngBiasKey
ElseIf UCase(TypeName(lngBiasKey)) = "VARIANT()" Then
    lngTZBias = 0
    For k = 0 To UBound(lngBiasKey)
       lngTZBias = lngTZBias + (lngBiasKey(k) * 256^k)
    Next
End If

'==========================================================================
' Connect to Active Directory
'==========================================================================
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
strBase = "<LDAP://" & strRootDomain & ">"

'==========================================================================
' Filter to exclude users that have "password never expires"
' or "password not required" set.
'==========================================================================
strFilter = "(&(objectCategory=person)(objectClass=user)" _
    & "(!userAccountControl:1.2.840.113556.1.4.803:=65536)" _
    & "(!userAccountControl:1.2.840.113556.1.4.803:=32))"
strAttributes = "employeeID,SN,givenName,sAMAccountName,cn,mail,pwdLastSet"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute

'==========================================================================
' Create the text file userpwd.txt in the C:\logs directory.
'==========================================================================
Set objFSO = CreateObject("Scripting.FilesystemObject")

If objFSO.FileExists("userpwd.txt") Then
Set objFile = objFSO.OpenTextFile("userpwd.txt", 2, True) 
Else
Set objFile = objFSO.CreateTextFile("userpwd.txt")
End If

Set objFile = Nothing
 
Set objFile = objFSO.OpenTextFile("userpwd.txt", 2, True)

eCounter=0

Do Until objRecordSet.EOF
    strName = objRecordset.Fields("samAccountName").Value
    strEmployeeID = objRecordset.Fields("employeeID").Value
    strEmailAddress = objRecordSet.Fields("mail").value
    strCN = objRecordSet.Fields("cn").Value
    
If strEmployeeID <> "" And strEmailAddress <> "" Then

    Set objPwdLastSet = objRecordset.Fields("pwdLastSet").Value

    strPasswordChangeDate = Integer8Date(objPwdLastSet, lngTZBias)
    intPassAge = DateDiff("d", strPasswordChangeDate, Now)
    
    CalcDate = (PasswordExpiry - intPassAge )
    strChangeDate = DateAdd("d",CalcDate,Now())
    strPWChangeDate = FormatDateTime(strChangeDate, vbLongDate)    
    intExpiresIn = PasswordExpiry - intPassAge
    If (intExpiresIn >= 1 And intExpiresIn <= 7) Or intExpiresIn = 14 Then
        objFile.WriteLine strName & vbCrLf & "Your password expires in " & intExpiresIn & " day"
        objFile.WriteLine strEmailAddress & vbCrLf
        Call SendEmailMessage(strEmailAddress, intExpiresIn)
        eCounter = eCounter + 1
    End If
End If
objRecordset.MoveNext
Loop

objConnection.Close

Function Integer8Date(objDate, lngBias)
    Dim lngAdjust, lngDate, lngHigh, lngLow

    lngAdjust = lngBias
    lngHigh = objDate.HighPart
    lngLow = objdate.LowPart
    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
    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

'==========================================================================
' SUBS AND FUNCTIONS
'==========================================================================

Sub SendEmailMessage(strDestEmail, strNoOfDays)
    
'    If (strDestEmail = "") Then
'        Wscript.Echo "No email address, no message sent."
'        Exit Sub
'    End If

    Set objMessage = CreateObject("CDO.Message")
    If strNoOfDays = 1 Then
      	objMessage.Subject = "Password Expires in " & strNoOfDays & " day"
    Else  
    	objMessage.Subject = "Password Expires in " & strNoOfDays & " days"
    End If

objMessage.Sender = "helpdesk@mycompany.org"
objMessage.To = strDestEmail

objMessage.TextBody = objMessage.TextBody & "On " & strPWChangeDate & ", the network password for loginname " & strName & " will expire on unclassified systems." & vbCrLf  
objMessage.TextBody = objMessage.TextBody & "Before that date (there is no grace period), please change your password." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "IMPORTANT: Do not use a password you have used before." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "If you have questions or need assistance, call the Computing Helpdesk, x6000." & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf 
objMessage.TextBody = objMessage.TextBody & "Instructions for Changing Your Network Password" & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf
objMessage.TextBody = objMessage.TextBody & "You must be connected to the mycompany network, either in the office or via VPN tunnel." & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf
objMessage.TextBody = objMessage.TextBody & "Windows 2000/XP" & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  1.  Press <Ctrl + Alt + Delete>." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  2.  In the window that opens, click Change Password." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  3.  As prompted, type your old password, type your new password" & vbCrLf 
objMessage.TextBody = objMessage.TextBody & "      (not one you have used before), and retype your new password" & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      to confirm it. Click OK." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  4.  When notified that your password has been successfully changed," & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      click OK." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  5.  Click Cancel to return to your work." & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf
objMessage.TextBody = objMessage.TextBody & "Macintosh" & vbCrLf
objMessage.TextBody = objMessage.TextBody & "Note: For an illustrated version of these instructions, see [URL unfurl="true"]http://intranet.mycompany.org/computing/passchg.html"[/URL] & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  1.  Make sure your mycompany email program is not running." & vbCrLf 
objMessage.TextBody = objMessage.TextBody & "  2.  In your Web browser, go to [URL unfurl="true"]https://pw.mycompany.org/iisadmpwd/aexp.htr"[/URL] & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      If prompted for your old and new passwords, skip to step 5." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      Otherwise continue at step 3." & vbCrLf   
objMessage.TextBody = objMessage.TextBody & "  3.  If a dialog box headed ""Connect to 'pw.mycompany.org' as"" appears:" & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      --In the User ID field type mycompany\loginname (example: mycompany\jdoe)." & vbCrLf 
objMessage.TextBody = objMessage.TextBody & "      --In the Password field type your current network password." & vbCrLf 
objMessage.TextBody = objMessage.TextBody & "      Click OK." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  4.  If a security notice appears, click OK or Continue." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  5.  The ""Changing Password..."" window opens, with your loginname in parentheses." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      --In the Old password field, type your current password." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "      --As prompted, type your new password twice." & vbCrLf
objMessage.TextBody = objMessage.TextBody & "  6.  Click Change." & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf
objMessage.TextBody = objMessage.TextBody & "What Is a Network Password?" & vbCrLf
objMessage.TextBody = objMessage.TextBody & vbCrLf
objMessage.TextBody = objMessage.TextBody & "A network password gives Mac and Windows users access to their email on an Exchange server" & vbCrLf
objMessage.TextBody = objMessage.TextBody & "and to network resources such as Shasta and Lassen drops. In addition," & vbCrLf
objMessage.TextBody = objMessage.TextBody & "Windows users need their network password to log in to the Windows network." & vbCrLf

objMessage.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
objMessage.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver")[/URL] = "mail.mycompany.org"
objMessage.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25
objMessage.Configuration.Fields.Update
objMessage.Send

End Sub 

strFile = "userpwd.txt"

Set file = objFSO.GetFile (strFile)
strFileDate = FormatDateTime(file.DateLastModified,vbShortDate)
strNow = FormatDateTime(Now,vbShortDate)

if strFileDate = strNow Then
	strStatus = "SUCCESSFUL"
Else
	strStatus = "UNSUCCESSFUL"
end If

Set objEmail = CreateObject("CDO.Message")
objEmail.Sender = "gmagerr@mycompany.org"
objEmail.To = "sysadmins@mycompany.org"
objEmail.Subject = "Password notification results " & strStatus
 
objEmail.HTMLBody = objEmail.HTMLBody & "Script ran on " & Date() & " from server mycompanysim.<BR>"
objEmail.HTMLBody = objEmail.HTMLBody & "<BR>"
objEmail.HTMLBody = objEmail.HTMLBody & eCounter & " notifications sent.<BR>"

objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserver")[/URL] = "mail.mycompany.org"
objEmail.Configuration.Fields.Item ("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25
objEmail.Configuration.Fields.Update
objEmail.Send

Set objEmail = Nothing
 
Now() is going to give you date/time and I can see there being a difference with the modified date of the file and what the value of Now() is when you compare them. If this will be run once a day then just compare the date values.

Look at DateValue(Now()) and DateValue(objFile.DateLastModified)

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Thanks dm4ever
I really don't want to use the text file date to notify of a success or failure. Is there a better way to do this?
Thanks.
 
I assume this is a script that runs on the DC nightly?

I would use one of two methods. For a general "this script ran un/successfully" message, you could go with an Event Log entry. This will tell you wether or not it ran and with what error it terminated with.

Code:
Set oShell = CreateObject("Wscript.Shell")
Const EVENT_SUCCESS = 0
Const EVENT_FAIL = 1
if err.number <> 0 then
  oShell.LogEvent EVENT_ERROR, "Passsword Checking script exited with an error." & vbcrlf & "Error Number: " & err.number & vbcrlf & "Error: " & err.description
else
   oShell.LogEvent EVENT_SUCCESS, "Passsword Checking script completed successfully."
end if

Or you could add "On Error Resume Next" right under "Option Explicit" and set an error trap near the end of your loop. If there is an error it logs it to a database/event log/flat file and then keeps on trucking with the rest of the script, logging each error as it runs into it.

All lessons learned from the School of Hard Knocks........at least tuition is cheap.
 
Thanks mishbaker

I'd like to include the success or failure in the body of the email I'm sending to the sysadmins group. We get an email every morning with this info, but it's based on the text file checking and I'm not too crazy about that. How would I go about doing that?

Thanks.
 
Or you could add "On Error Resume Next" right under "Option Explicit" and set an error trap near the end of your loop.
Never do this. You may live to regret it (or worse yet come back here with an impossible to diagnose problem).

Instead do something like:
Code:
'Other statements.
[COLOR=red]On Error Resume Next 'Disable default error handling.[/color]
'Statement to monitor.
[COLOR=red]If Err.Number = 0 Then
    On Error GoTo 0 'Resume default error handling.[/color]
    'Normal processing if no exception.
    'Normal.
    'Normal.
[COLOR=red]Else[/color]
    'Log error.  Don't resume default error handling yet
    'so you avoid clearing Err, or else capture the Err
    'properties you want to log into variables first.
[COLOR=red]    On Error GoTo 0 'Resume default error handling.
End If[/color]
'Other statements.
This is VBScript's rough "try/catch" equivalent.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top