newbindiaper Posted May 9, 2013 Posted May 9, 2013 (edited) Hi folks,I am having a strange problem. I am VERY new to scripting, and have inherited some scripts that are in production. All of a sudden, one of the scripts is not working and produces the errror "Variable used without being declared". I can't make any sense out of it because nothing has changed since the last time this script worked. I am hoping some of you might be kind enough to have a look at my code and help a total newb out of the woods.This script checks to see if a user has not logged in in at least 14 days, and if not the account will be disabled. The IF error (Variable used without being declared) occurs on line 39: If $DaysDiff > 14 or $ObjLastLogin = 0 ThenHere's the code:Dim $members = 0Dim $UserCount = 0#include <Date.au3>#include <Array.au3>#include <EventLog.au3>Global $EventLogApp, $aData[1] = [0]Global $EventLogApp = _EventLog__RegisterSource("", @ScriptName)If $EventLogApp <> 0 Then _EventLog__Report($EventLogApp, 4, 'None', "2000", @UserName, @ScriptName & " script ran successfully, Exit code " & @error, $aData)$UserCount = 0; ------------------------------------------------------------------------------If FileExists(@ScriptDir & "DisContractors.txt") Then FileDelete(@ScriptDir & "DisContractors.txt")$oMyError = ObjEvent("AutoIt.Error", "MyErrFunc"); Open ADO Connection to Active Directory$objCommand = ObjCreate("ADODB.Command")$objConnection = ObjCreate("ADODB.Connection")$objConnection.Provider = "ADsDSOObject"$objConnection.Open("Active Directory Provider"); ------------------------------------------------------------------------------_ADGetGroupMembers($members, "cn=genContractors, ou=General, ou=_SecGroups, dc=mydomain, dc=com", 0)$objConnection.Close; ------------------------------------------------------------------------------$objCommand = ObjCreate("ADODB.Command")$objConnection = ObjCreate("ADODB.Connection")$objConnection.Provider = "ADsDSOObject"$objConnection.Open("Active Directory Provider"); ------------------------------------------------------------------------------If $members[0] > 0 ThenFor $i = 1 To $members[0]$objUser = ObjGet("LDAP://" & $members[$i])If $objUser.AccountDisabled <> -1 Then$ObjLastLogin = $objUser.Get('lastLogonTimestamp')If $ObjLastLogin <> 0 Then$intLogonTime = $ObjLastLogin.HighPart * (2 ^ 32) + $ObjLastLogin.LowPart$intLogonTime = $intLogonTime / (60 * 10000000)$LastLoginDate = _DateAdd('n', Int($intLogonTime), "1601/01/01 00:00:00")$DaysDiff = _DateDiff('d', $LastLoginDate, _NowCalcDate())EndIfIf $DaysDiff > 14 or $ObjLastLogin = 0 Then$NewDescription = "User AutoDisabled " & @YEAR & "/" & @MON & "/" & @MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC$Description = $objUser.Get("description")If $Description = "" Then$objUser.Put("description", $NewDescription)$objUser.SetInfo()Else$objUser.Put("description", $NewDescription & " -- " & $Description)$objUser.SetInfo()EndIf$UserCount = $UserCount + 1$objUser.AccountDisabled = True$objUser.SetInfoFileWriteLine(@ScriptDir & "DisContractors.txt", @CRLF & $members[$i])EndIfEndIfNextEndIf$objCommand = 0$objConnection = 0; ------------------------------------------------------------------------------Sleep(2000)If $UserCount > 0 Then RunWait(@ScriptDir & 'bmail.exe -s smtp-int.mydomain.com -t ISAutomation@mydomain.com -f ADJanitor@mydomain.com -a "' & $UserCount & ' AD Accounts Auto Disabled - ' & @MON & '/' & @MDAY & '/' & @YEAR & '" -m "' & @ScriptDir & 'DisContractors.txt" -c'); ==============================================================================; _ADGetGroupMembers; Arguments,; $members - Array that the result will be stored in; $group - Group to retrieve members from; $sort - optional, default 0 : Set to 1 to sort the array; Returns an array to $members where $members[0] will be the number of users in the group and; $members[1] to $members[$members[0]] are the distinguished names of the usersFunc _ADGetGroupMembers(ByRef $members, $groupdn, $sort = 0);If _ADObjectExists($group) = 0 Then Return 0Local $oUsr, $objCommand, $groups$objCommand = ObjCreate("ADODB.Command")$objCommand.ActiveConnection = $objConnection$objCommand.Properties("Searchscope") = 2Dim $members[1]$i = 0While 1$rangemodifier = $i * 1000$range = "Range=" & $rangemodifier & "-" & $rangemodifier + 999$strCmdText = "<LDAP://" & $groupdn & ">;;member;" & $range & ";base"$objCommand.CommandText = $strCmdText$objRecordSet = $objCommand.Execute$membersadd = $objRecordSet.fields(0).ValueIf $membersadd = 0 Then ExitLoopReDim $members[uBound($members) + 1000]For $j = $rangemodifier + 1 To $rangemodifier + 1000$members[$j] = $membersadd[$j - $rangemodifier - 1]Next$i += 1$objRecordSet.CloseWEnd$rangemodifier = $i * 1000$range = "Range=" & $rangemodifier & "-*"$strCmdText = "<LDAP://" & $groupdn & ">;;member;" & $range & ";base"$objCommand.CommandText = $strCmdText$objRecordSet = $objCommand.Execute$membersadd = $objRecordSet.fields(0).ValueReDim $members[uBound($members) + UBound($membersadd)]For $j = $rangemodifier + 1 To $rangemodifier + UBound($membersadd)$members[$j] = $membersadd[$j - $rangemodifier - 1]Next$objRecordSet.Close$objCommand = 0$objRecordSet = 0$members[0] = UBound($members) - 1If $sort = 1 Then_ArraySort($members, 0, 1)EndIfReturn 1EndFunc ;==>_ADGetGroupMembers; ============================================================================Func MyErrFunc()$HexNumber = Hex($oMyError.number, 8)If $HexNumber = 80020009 ThenSetError(3)ReturnEndIfSelectCase $oMyError.windescription = "Access is denied."$objConnection.Close("Active Directory Provider")$objConnection.Open("Active Directory Provider")SetError(2)Case 1SetError(1)EndSelectGlobal $EventLogApp, $aData[1] = [0]Global $EventLogApp = _EventLog__RegisterSource("", "Application Error")If $EventLogApp <> 0 Then _EventLog__Report($EventLogApp, 1, "None", "1000", @UserName, "AutoTerm was unable to process terminations, Error " & @error, $aData)_EventLog__Close($EventLogApp)EndFunc ;==>MyErrFunc; ============================================================================Dim $members = 0Any help would be greatly appreciated!!!Thank you, Edited May 9, 2013 by newbindiaper
kylomas Posted May 9, 2013 Posted May 9, 2013 (edited) newbindiaper,I'm pretty sure that is not all of the code. i don't see an include for ADFunctions.au3. Maybe that's what you are missing.It would help if you used code tags for posting code and also posted the error message/console message.kylomasedit: disregard, brain lost again... Edited May 9, 2013 by kylomas Forum Rules Procedure for posting code "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals." - Sir Winston Churchill
BrewManNH Posted May 9, 2013 Posted May 9, 2013 This section of your code is the problem I'm guessing. If $ObjLastLogin <> 0 Then $intLogonTime = $ObjLastLogin.HighPart * (2 ^ 32) + $ObjLastLogin.LowPart $intLogonTime = $intLogonTime / (60 * 10000000) $LastLoginDate = _DateAdd('n', Int($intLogonTime), "1601/01/01 00:00:00") $DaysDiff = _DateDiff('d', $LastLoginDate, _NowCalcDate()) EndIf The only way that $DaysDiff gets declared is when $ObjLastLogon doesn't equal 0, which probably isn't happening all the time, so it errors out. You should declare all your variables before you use them, then you won't get this problem. Plus, you will make sure that they're scoped correctly, and that you didn't mistype a variable name. Add something like this line to the top of your script so that you will have better error checking #AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 6 If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag GudeHow to ask questions the smart way! I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from. Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays. - ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script. - Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label. - _FileGetProperty - Retrieve the properties of a file - SciTE Toolbar - A toolbar demo for use with the SciTE editor - GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI. - Latin Square password generator
MouseSpotter Posted May 9, 2013 Posted May 9, 2013 @newbindiaper: There has been a change to something (SciTE?) where now you must explicitly declare (local, global, dim) a variable before using it. Before this - you could simply create start using a variable without declaring it. So old script may fail because they did not follow use the explicit option. To resolve your issue - add Global $DaysDiff, $ObjLastLogin at the beginning of the script (or better ... track down the first usage and put the right local/global statement on the assignment).
Divine Posted May 9, 2013 Posted May 9, 2013 No, you don't NEED to include the Global, Local, or dim in front of the variables. You only have to include them when you are using the variables across multiple functions. Regardless, you should try declaring whether they are global, local, or dim. That might be your fix.
Divine Posted May 9, 2013 Posted May 9, 2013 @MouseSpotter No problem Now let's just hope that newbindiaper's script will be fixed from this.
guinness Posted May 9, 2013 Posted May 9, 2013 The user (if using SciTE4AutoIt3) should add the following to the top of the script. Actually all of you should be using Au3Check with these advanced parameters. #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 UDF List: _AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018
MouseSpotter Posted May 9, 2013 Posted May 9, 2013 The user (if using SciTE4AutoIt3) should add the following to the top of the script. Actually all of you should be using Au3Check with these advanced parameters. #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 WOW! Wonderful ... is there a way to make this the default for all scripts that do not explicitly set it?
Moderators Melba23 Posted May 9, 2013 Moderators Posted May 9, 2013 MouseSpotter,I have several personalised SciTE abbreviations which add various often-used lines to scripts - one of them adds this line. Look in the <SciTE Help - Extra Utilities - Abbreviation Manager> to see how you can create your own abbreviations to do the same. M23 Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind Open spoiler to see my UDFs: Spoiler ArrayMultiColSort ---- Sort arrays on multiple columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area
annaharris Posted May 9, 2013 Posted May 9, 2013 It is very important to declare all the variables at the start before using them and always remember to define their scope.
Moderators Melba23 Posted May 9, 2013 Moderators Posted May 9, 2013 annaharris,I would qualify that remark a little: "It is very important to declare all the Global variables at the start before using them "Sometimes it is better to declare variables other than at the very beginning of a script/function - for example if you are testing for the validity of passed parameters, why declare the necessary variables until you have confirmed that they are needed? M23 Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind Open spoiler to see my UDFs: Spoiler ArrayMultiColSort ---- Sort arrays on multiple columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area
Developers Jos Posted May 9, 2013 Developers Posted May 9, 2013 WOW! Wonderful ... is there a way to make this the default for all scripts that do not explicitly set it? Sure, just add the appropriate setting to AutoIt3Wrapper.ini located in the AutoIt3Wrapper directory. See attached AutoIt3Wrapper.ini.examples for all options. the current version of AutoIt3Wrapper.ini.examples probably doesn't contain them all. [Other] Run_AU3Check=Y AU3Check_Parameter=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 JosAutoIt3Wrapper.ini.example.txt SciTE4AutoIt3 Full installer Download page - Beta files Read before posting How to post scriptsource Forum etiquette Forum Rules Live for the present, Dream of the future, Learn from the past.
Moderators Melba23 Posted May 9, 2013 Moderators Posted May 9, 2013 Jos, A couple of rather out-dated ones in there: PassPhrase= Allow_Decompile= UseAnsi= M23 Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind Open spoiler to see my UDFs: Spoiler ArrayMultiColSort ---- Sort arrays on multiple columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area
Developers Jos Posted May 9, 2013 Developers Posted May 9, 2013 A couple of rather out-dated ones in there: Yea ...the good old times.... maybe they will come back, you never know SciTE4AutoIt3 Full installer Download page - Beta files Read before posting How to post scriptsource Forum etiquette Forum Rules Live for the present, Dream of the future, Learn from the past.
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now