Jump to content

Variable used without being declared


Recommended Posts

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 Then

Here's the code:

Dim $members = 0

Dim $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 Then

For $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())

EndIf

If $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.SetInfo

FileWriteLine(@ScriptDir & "DisContractors.txt", @CRLF & $members[$i])

EndIf

EndIf

Next

EndIf

$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 users

Func _ADGetGroupMembers(ByRef $members, $groupdn, $sort = 0)

;If _ADObjectExists($group) = 0 Then Return 0

Local $oUsr, $objCommand, $groups

$objCommand = ObjCreate("ADODB.Command")

$objCommand.ActiveConnection = $objConnection

$objCommand.Properties("Searchscope") = 2

Dim $members[1]

$i = 0

While 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).Value

If $membersadd = 0 Then ExitLoop

ReDim $members[uBound($members) + 1000]

For $j = $rangemodifier + 1 To $rangemodifier + 1000

$members[$j] = $membersadd[$j - $rangemodifier - 1]

Next

$i += 1

$objRecordSet.Close

WEnd

$rangemodifier = $i * 1000

$range = "Range=" & $rangemodifier & "-*"

$strCmdText = "<LDAP://" & $groupdn & ">;;member;" & $range & ";base"

$objCommand.CommandText = $strCmdText

$objRecordSet = $objCommand.Execute

$membersadd = $objRecordSet.fields(0).Value

ReDim $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) - 1

If $sort = 1 Then

_ArraySort($members, 0, 1)

EndIf

Return 1

EndFunc ;==>_ADGetGroupMembers

; ============================================================================

Func MyErrFunc()

$HexNumber = Hex($oMyError.number, 8)

If $HexNumber = 80020009 Then

SetError(3)

Return

EndIf

Select

Case $oMyError.windescription = "Access is denied."

$objConnection.Close("Active Directory Provider")

$objConnection.Open("Active Directory Provider")

SetError(2)

Case 1

SetError(1)

EndSelect

Global $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 = 0

Any help would be greatly appreciated!!!

Thank you,

Edited by newbindiaper
Link to comment
Share on other sites

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.

kylomas

edit: disregard, brain lost again...

Edited 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

Link to comment
Share on other sites

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 Gude
How 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

Link to comment
Share on other sites

@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).

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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 parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

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

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png 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 columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

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

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png 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 columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Developers

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

Jos

AutoIt3Wrapper.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.
  :)

Link to comment
Share on other sites

  • Moderators

Jos,

A couple of rather out-dated ones in there: ;)

PassPhrase=
Allow_Decompile=
UseAnsi=

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png 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 columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Developers

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.
  :)

Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...