AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development...

56
AutoIt v3: Your Quick Guide by Andy Flesner Copyright © 2007 O’Reilly Media, Inc. ISBN: 978-0-596-51512-6 Released: September 14, 2007 AutoIt is becoming increasingly popular in the system administration field as a tool for automating administrative tasks. Although this is one of its more popular uses, you can use AutoIt to automate anything in a Windows environment. This powerful scripting language can run any program and manipulate keyboard and mouse input. With its RunAs sup- port, administrators can perform unat- tended installations and configuration changes using embedded administrative privileges. This guide teaches you the foundations of the AutoIt v3 language. You will learn about variables and includes, graphical user interfaces, user-defined functions, and conditional and loop statements. You will then apply what you have learned in examples related to the system administration field. The examples in this Short Cut can be used to create any- thing from a game modification to a log- on script that verifies Windows updates. Contents Introduction and AutoIt History .......................................... 2 Variables and Includes ................... 2 Graphical User Interfaces (GUIs) ......................................... 10 Automation Examples .................. 35 Conclusion .................................. 55 Find more at shortcuts.oreilly.com

Transcript of AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development...

Page 1: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

AutoIt v3: YourQuick Guideby Andy Flesner

Copyright © 2007 O’Reilly Media, Inc.

ISBN: 978-0-596-51512-6

Released: September 14, 2007

AutoIt is becoming increasingly popularin the system administration field as atool for automating administrative tasks.Although this is one of its more popularuses, you can use AutoIt to automateanything in a Windows environment.This powerful scripting language can runany program and manipulate keyboardand mouse input. With its RunAs sup-port, administrators can perform unat-tended installations and configurationchanges using embedded administrativeprivileges.

This guide teaches you the foundationsof the AutoIt v3 language. You will learnabout variables and includes, graphicaluser interfaces, user-defined functions,and conditional and loop statements.You will then apply what you havelearned in examples related to the systemadministration field. The examples inthis Short Cut can be used to create any-thing from a game modification to a log-on script that verifies Windows updates.

Contents

Introduction and AutoItHistory .......................................... 2Variables and Includes ................... 2Graphical User Interfaces(GUIs) ......................................... 10Automation Examples .................. 35Conclusion .................................. 55

Find more at shortcuts.oreilly.com

Page 2: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Introduction and AutoIt HistoryAutoIt started in late 1998 as a C-compiled program used to automate keystrokesduring software installations. In January 1999, the AutoIt team released AutoIt v1,which included the Send, Run, RunWait, WinWait, WinWaitClose, WinWaitActive,WinHide, WinActivate, WinClose, WinRestore, Sleep and SetKeyDelay functions. Au-toIt v2 was released in August that same year and included the first version ofAutoItX, which offered DLL/COM control. Over the next two years, massive up-dates to AutoIt v2 added many new functions to the language. In May 2001, theAutoIt source code was completely rewritten in C++ and development stalled until2003, when the first beta version of AutoIt v3 was released. Over 100 beta versionslater, the AutoIt developers released AutoIt v3 in February of 2004. February of2005 marked the release of AutoIt v3.1.0, which added the capability of graphicaluser interface (GUI) creation. This version was the most notable release becauseit brought AutoIt to the forefront of the scripting world and made it a rival to VisualBasic Scripting, batch files, and other popular scripting languages. AutoIt is freeto use and has a strong and helpful community base.

This Short Cut is a guide for AutoIt v3.2.4.9, released on May 25, 2007. Downloadthe latest version of AutoIt here: http://www.autoitscript.com/autoit3/downloads.php

I recommend using the SciTE AutoIt3 Editor for writing scripts. It has an extensivehelp file and color-codes everything nicely. You can download the latest SciTEAutoIt3 Editor here: http://www.autoitscript.com/autoit3/scite/downloads.php

Variables and IncludesA variable is simply a named placeholder for a string or array of data. You can usea variable as many times as you need within a script and it only requires declarationonce. This allows you to manage and manipulate data in a centralized location ifdesired.

Variables are a necessity if you want to write robust scripts that are fairly simpleto modify. For example, defining a filename as a variable allows you to change thefilename from a single location instead of changing many static entries. (Usingstatic data entries can lead to problems.) Example 1 installs two Windows XPSecurity updates. Example 2 performs the same operations, but does so usingvariables. You may not yet understand everything displayed in the examples; theyare only meant to show that replacing filenames with variables is one way to sim-plify your code.

AutoIt v3: Your Quick Guide 2

Page 3: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Example 1. Windows Update Automation

If @Username <> "Administrator" Then RunAsSet("Administrator",@ComputerName,"password") install() RunAsSet()Else install()EndIf

Func install() RunWait("Windows Update 1.exe /passive /norestart") RunWait("Windows Update 2.exe /passive /norestart")EndFunc

Example 2. Windows Update Automation Using Variables

Global $admin, $password, $program, $program2

$admin = "Administrator"$password = "password" ; change password to the password for theAdministrator account; change the following program names to the actual filenames of 2 Windows updates$program = "Windows Update 1.exe /passive /norestart"$program2 = "Windows Update 2.exe /passive /norestart"

If @Username <> "Administrator" Then RunAsSet($admin,@ComputerName,$password) install() RunAsSet()Else install()EndIf

Func install() RunWait($program) RunWait($program2)EndFunc

Note how modifying the variables listed in the variable declarations can changethe program names. This practice becomes more useful as you develop more com-plicated scripts.

Variable Types—Dim, Global, and LocalThere are three types of variables in AutoIt:

Dim

Declaring a variable using Dim gives it the scope of its current location withinthe script. If the variable is declared outside any functions, its scope is global.

AutoIt v3: Your Quick Guide 3

Page 4: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

The following is an example of declaring a Dim variable in the global scope. Itruns setup.exe in the directory where the script is located:

Dim $variable = @ScriptDir & "\setup.exe" Run($variable)

The next example shows how declaring a Dim variable inside a function allowsit only Local scope and how the variable is destroyed once the function is com-plete. The result is a script that errors out when run because $variable is notdeclared globally:

function()

Func function() Dim $variable = @ScriptDir & "\setup.exe" EndFunc

Run($variable)

You should explicitly declare variables as Global or Local to avoid problems. Ifa Dim variable is declared inside a function but a Global variable already exists,the Global variable is overwritten. The following example shows what happensif a Global variable exists when the same variable is declared as Dim within afunction. The result is that setupbad.exe runs instead of setup.exe; the Global$variable is modified to setupbad.exe because Dim was used to declare the var-iable locally within the function:

Global $variable = @ScriptDir & "\setup.exe"

function()

Func function() Dim $variable = @ScriptDir & "\setupbad.exe" EndFunc

Run($variable)

Global

This type of variable can be read from or written to from anywhere in the script.Global variables can be used in functions without being destroyed when thefunctions complete. The following is an example of declaring a Global variable:

Global $variable = 2

Local

A Local variable is used in the scope of a function. Once the function is com-plete, the variable is destroyed. If a Global variable of the same name already

AutoIt v3: Your Quick Guide 4

Page 5: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

exists, the function modifies the Global variable and it is not destroyed whenthe function completes. Variables are always checked in the local scope first,then in the global scope. The following example shows the use of a Local var-iable within a function:

function()

Func function() Local $variable = @ScriptDir & "\setup.exe" Run($variable) EndFunc

AutoIt Variable Explicit Declaration Is Not Required

AutoIt does not require the explicit declaration of variables. However, as adebugging measure it is wise to explicitly declare all variables used within ascript. If you do not explicitly declare variables, it can become very difficultto find a mistyped variable name that may be causing your script to error onexecution. You should include the following in your scripts to require theexplicit declaration of variables in order to avoid bugs:

Opt("MustDeclareVars", 1)

With this option enabled, all variables must now be explicitly declared usingGlobal, Local, or Dim.

ConstantsA constant is a variable that never changes. It remains a static value for the entirescript execution. You cannot change the value of a constant, nor can you convertan existing variable into a constant. Placing Const after Dim, Global or Local makesthe variable a constant. You can also declare a constant variable without explicitdeclaration. The following example illustrates how to declare a constant variablein each scenario:Const $example = 0Dim Const $example1 = 1Global Const $example2 = 2Local Const $example3 = 3

ArraysAn array is a matrix of data in which all the elements are of the same data type andsize. For example, an array of two numbers—“5” and “3”—is declared as follows:$num[0] = "5"$num[1] = "3"

AutoIt v3: Your Quick Guide 5

Page 6: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Arrays can also be multidimensional, with up to 64 dimensions. Example 3 showsa two-dimensional array.

Example 3. Two-Dimensional Array

$letter[0][0] = "w"$letter[0][1] = "x"$letter[1][0] = "y"$letter[1][1] = "z"

A visual representation of Example 3 would be a 2×2 matrix as displayed inFigure 1.

Note

Variants—Arrays with Differing Data Types

An array using different data types is known as a variant and can containanything from a number to a Boolean value. Variants are not restricted inAutoIt; however, they are not recommended. Using differing data types inan array—especially arrays within an array—can dramatically decrease theexecution speed of your scripts.

Finding the Correct IncludeIncludes are files that contain prewritten functions for AutoIt. Think of them asfunctions written into your script that you can call to perform actions for you. Youcan utilize these files by adding them to your script with the following:#include <filename.au3>

Table 1 lists the standard includes that accompany the AutoIt v3 installation.

Figure 1. Visual representation of Example 3. Two-Dimensional Array

AutoIt v3: Your Quick Guide 6

Page 7: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Table 1. AutoIt v3 Standard Includes

Include Description

Array.au3 Functions that assist with array management

AVIConstants.au3 AVI Constants

ButtonConstants.au3 Button Constants

Color.au3 Functions that assist with color management

ComboConstants.au3 ComboBox Constants

Constants.au3 Various AutoIt Constants

Date.au3 Functions that assist with dates and times

DateTimeConstants.au3 DateTime Control Constants

EditConstants.au3 Edit Constants

File.au3 Functions that assist with files and directories

GuiCombo.au3 Functions that assist with ComboBox

GUIConstants.au3 Includes all GUI related constants

GUIConstantsEx.au3 Constants to be used in GUI applications

GUIDefaultConstants.au3 GUI default control styles

GuiEdit.au3 Functions that assist with Edit control

GuiIPAddress.au3 Used to create a GUI IP Address Control

GuiList.au3 Functions that assist with Listbox

GuiListView.au3 Functions that assist with ListView

GuiMonthCal.au3 Functions that assist with MonthCal

GuiSlider.au3 Functions that assist with Slider Control “Trackbar”

GuiStatusBar.au3 Functions that assist with the Statusbar control

GuiTab.au3 Functions that assist with the Tab Control

GuiTreeView.au3 Functions that assist with TreeView

IE.au3 Internet Explorer Automation UDF Library for Auto-It3

Inet.au3 Functions that assist with the Internet

ListBoxConstants.au3 ListBox Constants

ListViewConstants.au3 ListView Constants

Math.au3 Functions that assist with mathematical calculations

AutoIt v3: Your Quick Guide 7

Page 8: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Include Description

Memory.au3 Memory management routines

Misc.au3 Functions that assist with Common Dialogs

Process.au3 Functions that assist with process management

ProgressConstants.au3 Progress Constants

SliderConstants.au3 Slider Constants

Sound.au3 Functions that assist with Sound files

SQLite.au3 Functions that assist access to an SQLite database

SQLite.dll.au3 Inline SQLite3.dll

StaticConstants.au3 Static Constants

StatusBarConstants.au3 StatusBar Constants

String.au3 Functions that assist with String manipulation

TabConstants.au3 Tab Constants

TreeViewConstants.au3 TreeView Constants

UpDownConstants.au3 UpDown Constants

Visa.au3 VISA (GPIB & TCP) library

WindowsConstants.au3 Windows Constants

FileInstall—Including Files in AutoIt ScriptsThe FileInstall() function allows the inclusion of any file—such as an executableor image file—in the compiled script executable. This is similar to #include, butit dramatically increases the size of your compiled executable in most cases. Thisis the syntax of the FileInstall() function:FileInstall("sourcefile","destination" [,flag])

The flags for FileInstall() are optional. A flag of 0 tells the function not to over-write existing files. Use a flag of 1 if you would like to overwrite any existing filesthe script may encounter. The source file cannot be a variable; it must be a string,and it cannot contain wildcards.

Example 4 is an installation you can perform with the FileInstall() function thatextracts all installation files to the temp directory. When compiled, the entire in-stallation is a single executable.

Example 4. Using the FileInstall() Function

#NoTrayIconOpt("MustDeclareVars", 1)

AutoIt v3: Your Quick Guide 8

Page 9: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

FileInstall("C:\Documents and Settings\Administrator\Desktop\Program\" & _"Setup.exe", @TempDir & "\Setup.exe", 1)FileInstall("C:\Documents and Settings\Administrator\Desktop\Program\" & _"Setup.exe", @TempDir & "\setup.ico", 1)FileInstall("C:\Documents and Settings\Administrator\Desktop\Program\" & _"Setup.exe", @TempDir & "\setup.ini", 1)FileInstall("C:\Documents and Settings\Administrator\Desktop\Program\" & _"Setup.exe", @TempDir & "\program.dll", 1)FileInstall("C:\Documents and Settings\Administrator\Desktop\Program\" & _"Setup.exe", @TempDir & "\readme.txt", 1)

Run(@TempDir & "\Setup.exe")WinWait("Installation Wizard", "Welcome to the")If Not WinActive("Installation Wizard", "Welcome to the") Then _WinActivate("Installation Wizard", "Welcome to the")WinWaitActive("Installation Wizard", "Welcome to the")ControlClick("Installation Wizard", "", "Next")WinWait("Installation Wizard", "Installation Complete")If Not WinActive("Installation Wizard", "Installation Complete") Then _WinActivate("Installation Wizard", "Installation Complete")WinWaitActive("Installation Wizard", "Installation Complete")ControlClick("Installation Wizard", "", "Finish")

In this example, FileInstall() copies five files to the temp directory, then the Run() command runs Setup.exe. The program then waits for the installation wizard toappear using WinWait() and makes it active using WinActivate() before clickingNext with ControlClick() and then Finish with ControlClick() to complete theinstallation.

Line Continuation

An underscore ( _ ) signals that the current line of code continues onto thenext line. This practice keeps code clean and alleviates line wrapping and/or lines running off the side of the screen when writing or editing scripts.

If the line being separated is a string, it must be closed and linked to a newstring on the following line, as shown in this example:

Incorrect:"string _continuation of string"

Correct:"string" & _"continuation of string"

AutoIt v3: Your Quick Guide 9

Page 10: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Graphical User Interfaces (GUIs)One of the newest features of AutoIt is its ability to create graphical user interfaces.This feature adds an extraordinary amount of possibilities to the already usefulAutoIt language. Some of the most common uses of a GUI are installation menus,input forms, and progress bars.

I am beginning this section with an example so you can see the layout of GUI creationand get familiar with the functions used to create GUIs. Example 5 displays a two-button GUI with instructions and an image. It can be modified and used for anythingyou can use a two-button chooser for: an installer for two different programs, achooser for two different types of users, etc. You can easily increase the size of theGUI and create more buttons. You will learn what each GUI function does and howto configure each of them later on in Example 8.

Example 5. Graphical User Interface—Ai Smart Homes

; Includes the GuiConstants (required for GUI function usage)#include <GuiConstants.au3>

; Hides tray icon#NoTrayIcon

; Change to OnEvent modeOpt('GUIOnEventMode', 1)

; GUI CreationGuiCreate("Ai Smart Homes - Saint Louis, Missouri", 400, 300)GuiSetIcon("icon.ico")

; Runs the GUIExit() function if the GUI is closedGUISetOnEvent($GUI_EVENT_CLOSE, 'GUIExit')

; Logo / PicGuiCtrlCreatePic("logo.jpg",120,5,156,160)

; InstructionsGUICtrlCreateLabel("Please Choose an Option Below:", 50, 180, 300, 15, $SS_CENTER)GUICtrlSetColor(−1,0xFF0000) ; Makes instructions Red

; Button1GUICtrlCreateButton("Visit Our Website", 100, 210, 200, 30)GUICtrlSetOnEvent(−1, 'website') ; Runs website() when pressed

; Button2GUICtrlCreateButton("Send an Email", 100, 250, 200, 30)GUICtrlSetOnEvent(−1, 'email') ; Runs email() when pressed

AutoIt v3: Your Quick Guide 10

Page 11: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Func website() ; Hides the GUI while the function is running GUISetState(@SW_HIDE) Run("C:\Program Files\Internet Explorer\iexplore.exe www.aismarthomes.com") ExitEndFunc

Func email() ; Hides the GUI while the function is running GUISetState(@SW_HIDE) Run("mailto:[email protected]") ExitEndFunc

; Shows the GUI after the function completesGUISetState(@SW_SHOW)

; Idles the script in an infinite loop - this MUST be included when usingOnEvent modeWhile 1 Sleep(500)WEnd

; This function makes the script exit when the GUI is closedFunc GUIExit() ExitEndFunc

Figure 2 displays the GUI created by Example 5. Assuming logo.jpg is in the samedirectory as the *.au3 script file when it is compiled, a logo is displayed on the GUIas shown.

Figure 2. Output of Example 5. Graphical User Interface—Ai Smart Homes

AutoIt v3: Your Quick Guide 11

Page 12: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Note

Comments in a Script

Comments in an AutoIt script can be denoted in two ways:

1. Semicolon. The semicolon denotes the beginning of a comment on asingle line. Anything following a semicolon on a single line is commen-ted. If your comment runs onto the next line, you must begin that linewith another semicolon or the script reads that line as code and mostlikely errors upon execution.

2. #comments-start and #comments-end (also denoted as #cs and #ce).These commands comment an entire section of text within a script onmultiple lines. Anything after #comments-start or #cs is commenteduntil #comments-end or #ce is used to close the comment.

GUI Event ModesHow do you make something happen when a button is clicked on your GUI? Thereare two different event modes you can use to cause a reaction in your script whena button is pressed:

1. MessageLoop (default). This is the default mode; it causes the GUI only torespond to events if the GuiGetMsg() function is called. It is wise to call thisfunction many times per second in a loop; otherwise, you will have a slow orunresponsive GUI. The following loop continuously calls the GuiGetMsg()function until one of the two buttons are pressed or the user attempts to closethe GUI:

While 1 $guimsg = GuiGetMsg() Select Case $guimsg = $GUI_EVENT_CLOSE Exit ; closes the GUI Case $guimsg = $button1 button1(); runs button1 function Case $guimsg = $button2 button2(); runs button2 function EndSelect WEnd

Notice that the loop is infinite (noted by While 1; you will learn more aboutthis in the Conditional and Loop Statements section later in the Short Cut).The $guimsg variable will be continuously updated by the GuiGetMsg() func-tion until one of the three cases is satisfied. Choosing Button1 or Button2

AutoIt v3: Your Quick Guide 12

Page 13: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

causes a respective function to run. Closing the GUI causes the program toexit. Example 6 incorporates the GuiGetMsg() loop into a fully functionalscript.

Example 6. The GuiGetMsg() Method

; Includes the GuiConstants (required for GUI function usage)#include <GuiConstants.au3>

; GUI CreationGuiCreate("Menu", 400, 150)

; Button1$button1 = GUICtrlCreateButton("Button1", 100, 20, 200, 30)

; Button2$button2 = GUICtrlCreateButton("Button2", 100, 70, 200, 30)

; Shows the GUI after creationGUISetState(@SW_SHOW)

Func Function1() ; Hides the GUI while the function is running GUISetState(@SW_HIDE) ; ================ ; The script you would like to perform for Button1 goes here ; ================EndFunc

Func Function2() ; Hides the GUI while the function is running GUISetState(@SW_HIDE) ; ================ ; The script you would like to perform for Button2 goes here ; ================EndFunc

While 1 $guimsg = GuiGetMsg() Select Case $guimsg = $GUI_EVENT_CLOSE Exit ; closes the GUI Case $guimsg = $button1 function1(); runs Button1 function Case $guimsg = $button2 function2(); runs Button2 function EndSelect WEnd

AutoIt v3: Your Quick Guide 13

Page 14: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

2. OnEvent. Denoted by AutoItSetOption('GUIOnEventMode', 1), OnEvent modebasically pauses the script when something is chosen on the GUI and runs afunction. Once the function is completed, the main script resumes. Exam-ple 7 shows how to properly use OnEvent mode in a script similar toExample 6.

Example 7. The GUIOnEventMode Method

; Includes the GuiConstants (required for GUI function usage)#include <GuiConstants.au3>

; Changes to OnEvent modeOpt('GUIOnEventMode', 1)

; GUI CreationGuiCreate("Menu", 400, 150)

; Runs the GUIExit() function if the GUI is closedGUISetOnEvent($GUI_EVENT_CLOSE, 'GUIExit')

; Button1GUICtrlCreateButton("Button1", 100, 20, 200, 30)GUICtrlSetOnEvent(−1, 'Function1') ; run Function1 when pressed

; Button2GUICtrlCreateButton("Button2", 100, 70, 200, 30)GUICtrlSetOnEvent(−1, 'Function2') ; run Function2 when pressed

Func Function1() ; Hides the GUI while the function is running GUISetState(@SW_HIDE) ; ================ ; The script you would like to perform for Button1 goes here ; ================EndFunc

Func Function2() ; Hides the GUI while the function is running GUISetState(@SW_HIDE) ; ================ ; The script you would like to perform for Button2 goes here ; ================EndFunc

; Shows the GUI after the function completesGUISetState(@SW_SHOW)

; Idles the script in an infinite loop - this MUST be included when using; OnEvent mode

AutoIt v3: Your Quick Guide 14

Page 15: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

While 1 Sleep(500)WEnd

; This function makes the script exit when the GUI is closedFunc GUIExit() ExitEndFunc

Notice the While 1 loop again, just like in MessageLoop mode. This time, instead ofrefreshing a variable with the GuiGetMsg() function continuously, OnEvent moderefreshes the Sleep(500) command (which is a 500 ms timeout) until an eventoccurs. If Button1 or Button2 are pressed, their corresponding functions will run.If the GUI is closed, the script will exit.

Both Example 6 and Example 7 create the GUI shown in Figure 3. Both scriptsperform the same actions, but each uses a different event mode.

When creating a GUI, it is important to decide which type of event mode to use.Both methods work in any case, but MessageLoop tends to be more suited for ascript where the GUI is the main focus. In a script where the GUI is not the mainor only focus, OnEvent mode tends to be the better solution. In the end, both meth-ods perform the same set of tasks; they just go about them in different ways.Choosing between OnEvent and MessageLoop mode is, in most cases, a personalpreference.

GUI ControlsTable 2 lists the controls available in AutoIt, their descriptions, and their associ-ated functions.

Figure 3. Output from Example 6. The GuiGetMsg() Method and Example 7. TheGUIOnEventMode Method

AutoIt v3: Your Quick Guide 15

Page 16: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Table 2. AutoIt GUI Controls

Control Description Function

AVI Video Clip Inserts an AVI video clip GuiCtrlCreateAvi()

Button creates a button GuiCtrlCreateButton()

Checkbox creates a checkbox GuiCtrlCreateCheckbox()

Combo Box Creates a combo box GuiCtrlCreateComboBox()

Context Menu Creates a context (right-click)menu for a control of the entireGUI

GuiCtrlCreateContextMenu()

Date Creates a date control GuiCtrlCreateDate()

Dummy Creates a dummy control GuiCtrlCreateDummy()

Edit Creates an edit control GuiCtrlCreateEdit()

Group Creates a group control GuiCtrlCreateGroup()

Icon Creates an icon GuiCtrlCreateIcon()

Input Creates an input box GuiCtrlCreateInput()

Label Creates a static text control GuiCtrlCreateLabel()

List Creates a list control GuiCtrlCreateList()

List View Creates a list GuiCtrlCreateListView()

List View Item Creates a list item GuiCtrlCreateListViewItem()

Menu Creates a menu GuiCtrlCreateMenu()

Menu Item Creates an item for a menu or con-text menu

GuiCtrlCreateMenuItem()

Object—ActiveX

Creates an ActiveX control GuiCtrlCreateObj()

Picture Inserts a picture GuiCtrlCreatePic()

Progress Bar Inserts a progress bar GuiCtrlCreateProgress()

Radio Button Inserts a radio button GuiCtrlCreateRadio()

Slider Inserts a slider GuiCtrlCreateSlider()

Tab Creates a tab control GuiCtrlCreateTab()

Tab Item Creates a tab in a tab control GuiCtrlCreateTabItem()

Tree View Creates a tree view control GuiCtrlCreateTreeView()

AutoIt v3: Your Quick Guide 16

Page 17: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Control Description Function

Tree View Item Creates a tree view item GuiCtrlCreateTreeViewItem()

Up / Down Creates an up/down list control GuiCtrlCreateUpdown()

Example 8 contains examples of every AutoIt GUI control. Each item within theexample is labeled with a comment above it. To learn more about the differentoptions of each control, look them up in the AutoIt help file.

Example 8. Complete GUI Controls

#include <GuiConstants.au3>

; GUI CreationGuiCreate("GUI Control Examples", 500, 420)GuiSetIcon(@WindowsDir & "\explorer.exe", 0)

; Menu Creation$filemenu = GUICtrlCreateMenu("File")GUICtrlCreateMenuitem("Example File Menu Item",$filemenu)

; Context Menu$contextmenu = GUICtrlCreateContextMenu()

; Context Menu ItemGUICtrlCreateMenuitem("Example1",$contextmenu)GUICtrlCreateMenuitem("",$contextmenu) ; separatorGUICtrlCreateMenuitem("Example2",$contextmenu)

; Tab CreationGUICtrlCreateTab(0,0,500,400)

; Tab 1 Creation; ===================GUICtrlCreateTabItem("AVI,Button,Checkbox,ComboBox")

; AVIGUICtrlCreateAvi(@WindowsDir & "\clock.avi",-1,10,30,321,321,$ACS_AUTOPLAY)GUICtrlCreateLabel("AVI Example",140,355,60,15)

; ButtonGUICtrlCreateButton("Button Example",350,30,120,30)

; CheckboxGUICtrlCreateCheckbox("Checkbox Example",350,70,120,30)

; Combo BoxGUICtrlCreateCombo("ComboBox Example",350,110,120,30)

AutoIt v3: Your Quick Guide 17

Page 18: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

; Tab 2 Creation; ===================GUICtrlCreateTabItem("Group,Date,Dummy,Edit,Icon,Input,List,ListView")

; Start GroupGUICtrlCreateGroup("Group Example",20,40,460,60)

; DateGUICtrlCreateDate("",30,60,200,25)

; Dummy$dummybutton = GUICtrlCreateButton("Dummy Example",270,60,200,25)$dummy = GUICtrlCreateDummy()

; Close GroupGUICtrlCreateGroup("",-99,-99,1,1)

; EditGUICtrlCreateEdit("Edit Example",30,120,440,60)

; IconGUICtrlCreateIcon(@WindowsDir & "\Cursors\drum.ani",-1,30,200,32,32)GUICtrlCreateLabel("Icon Example",70,210,80,20)

; InputGUICtrlCreateInput("Input Example",160,205,300,20)

; ListGUICtrlCreateList("List Example",30,240,440,80)

; List View$listview = GUICtrlCreateListView("List View Example",30,330,440,60)

; List View ItemGUICtrlCreateListViewItem("List View Item Example",$listview)

; Tab 3 Creation; ===================GUICtrlCreateTabItem("ActiveX Object")

; ActiveX ObjectGUICtrlCreateLabel("ActiveX Object Example",10,30,140,20)$ie = ObjCreate("Shell.Explorer.2")$GUIActiveX = GUICtrlCreateObj($ie,10,50,480,340)$ie.navigate("http://www.aismarthomes.com")

; Tab 4 Creation; ===================GUICtrlCreateTabItem("Picture,Progress,Radio,Slider,TreeView,Updown")

AutoIt v3: Your Quick Guide 18

Page 19: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

; PictureGUICtrlCreatePic(@WindowsDir & "\Blue Lace 16.bmp",10,30,40,40)GUICtrlCreateLabel("Picture Example",55,45,80,20)

; Progress BarGUICtrlCreateLabel("Progress Example",400,70,90,20)$progress = GUICtrlCreateProgress(10,90,480,25)GUICtrlSetData($progress,33)

; RadioGUICtrlCreateRadio("Radio Example",10,140,90,20)

; SliderGUICtrlCreateLabel("Slider Example",290,170,100,20)GUICtrlCreateSlider(180,130,280,30)

; Tree ViewGUICtrlCreateLabel("Tree View Example",10,200,120,20)$treeview = GUICtrlCreateTreeView(10,220,480,60)

; Tree View Item$treetoplevel = GUICtrlCreateTreeViewItem("Tree View Example",$treeview)GUICtrlCreateTreeViewItem("Subitem1",$treetoplevel)GUICtrlCreateTreeViewItem("Subitem2",$treetoplevel)

; Up/DownGUICtrlCreateLabel("Example Updown",10,300,100,20)$updowninput = GUICtrlCreateInput("0",10,320,480,60)GUICtrlCreateUpdown($updowninput)

; Close TabsGUICtrlCreateTabItem("")

; Display GUIGuiSetState(@SW_SHOW)

; Continuous Loop to check for GUI EventsWhile 1 $guimsg = GUIGetMsg() Select Case $guimsg = $dummybutton GUICtrlSendToDummy($dummy) Case $guimsg = $dummy MsgBox(0,"Dummy Example","You have clicked the dummy button.") Case $guimsg = $GUI_EVENT_CLOSE Exit EndSelectWend

AutoIt v3: Your Quick Guide 19

Page 20: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

When run, Example 8 outputs the four tabs shown in Figure 4.

Manipulating Data in GUIsWhile creating a GUI, you must assign a variable to any controls that are used asdata in a function. For example, when creating a combo box, assigning a variableto it allows its value to be checked during a GuiCtrlRead() function. Example 9shows how to perform an action based on the value of a combo box.

Example 9. GuiCtrlRead()

#include <GuiConstants.au3>

; GUI CreationGuiCreate("Combo Example",200,80); Combo Box Creation$combobox = GuiCtrlCreateCombo("Notepad",10,10,120,20)GuiCtrlSetData(−1,"Paint|Command Prompt")

; Button Creation$button = GuiCtrlCreateButton("Go",10,40,60,20)

Figure 4. Complete GUI Controls Output

AutoIt v3: Your Quick Guide 20

Page 21: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

GUISetState(@SW_SHOW)

; Continuous Loop to check for GUI EventsWhile 1 $guimsg = GUIGetMsg() Select Case $guimsg = $button MsgBox(0,"","You chose " & GUICtrlRead($combobox) & ".") Select Case GUICtrlRead($combobox) = "Notepad" Run("notepad.exe") Exit Case GUICtrlRead($combobox) = "Paint" Run("mspaint.exe") Exit Case GUICtrlRead($combobox) = "Command Prompt" Run("cmd.exe") Exit EndSelect Case $guimsg = $GUI_EVENT_CLOSE Exit EndSelectWend

Notice the Select...Case that performs actions based on the GUICtrlRead($combobox) function. It is nested within the initial Select...Case statement thatperforms actions based on the GUIGetMsg() function. Example 9 outputs the com-bo box shown in Figure 5.

User FunctionsFunctions can be called at any time throughout a script any number of times.AutoIt comes with predefined functions that perform many different tasks. Thereare also many user-defined functions created by the AutoIt community. Thesefunctions were written by AutoIt users and increase the functionality of AutoIt.You must use the #include command when using these user-defined functions ina script. You can also create your own functions.

Figure 5. Output of Example 9. GuiCtrlRead()

AutoIt v3: Your Quick Guide 21

Page 22: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Creating Functions—Func, Return, EndFuncThe syntax of a User-Defined Function is as follows:Func functioname ( [Const] [ByRef] $param1, ..., [Const] [ByRef]$paramN,_$optionalpar1 = value, ...) ... [Return [value]]EndFunc

The following subsections explain the different components of a function.

Const and ByRefBoth Const and ByRef can apply to a single parameter and the order in which theyare written makes no difference. Please keep the following in mind when usingConst and ByRef:

• Const is optional, and only a variable declared as Const can be passed to aConst parameter in a function.

• ByRef is also optional, and it requires that the input of its parameter is a variable.When you use this option, any changes are reflected to the original variable.By default, a copy of the variable is used inside the function.

ParametersIf a parameter is not set with a default value, then it must be declared when callingthe function. A parameter with a default value is known as an optionalparameter. For instance, the following function uses variables with default valuesand can be called using those default values as function(). When the function isrun, a message box pops up stating that the value of $z is 5:Func function($x = 2, $y = 3) $x + $y = $z MsgBox(0,"$z's value",$z)EndFunc

The variables can still be declared differently, but defaults are used if the variablesare not explicitly expressed when calling the function. When the function ischanged as follows, variables must be declared when calling the function. An ex-ample of correctly calling this function is function(5,3) and the resulting messagebox would display a value of 8. If either $x or $y is not declared, the function doesnot run properly:Func function($x, $y) $x + $y = $z\ MsgBox(0,"$z's value",$z)EndFunc

AutoIt v3: Your Quick Guide 22

Page 23: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

ReturnUse Return to exit the function. The default return value in a user-defined functionis 0, but the return value can be specified. The following example displays a mes-sage box with the current user’s username:MsgBox(0,"Currently logged on user",user())

Func user() $user = @UserName Return $userEndFunc

User-Defined FunctionsThere are many user-defined function (UDF) libraries available on the AutoIt fo-rums. You can find a list of current AutoIt UDF collections here: http://www.autoitscript.com/forum/index.php?showtopic=45167. The following list de-scribes some of these UDF libraries:

Auto3Lib

Developed by Paul Campbell (username PaulIA), this UDF library includes over1,200 functions, including Animation controls, DateTime controls, Headercontrols, IPAddress controls, Listbox controls, ListView controls, Menus,Month Calendar controls, ProgressBar controls, StatusBar controls, Tab con-trols, ToolbarWindow controls, ToolTip controls, Tree View controls, andmany more.

SysTray_UDF

Developed by user Tuape, this UDF library allows you to read info from systemtray icons and remove them.

Microsoft Word Automation Library

Developed by Bob Anthony (username big_daddy), this UDF library allows youto create and manipulate Microsoft Word documents.

ExcelCOM_UDF

Developed by user Locodarwin, this UDF library allows you to create and ma-nipulate Microsoft Excel workbooks.

I have created a sample UDF to find a specific image on-screen based on its PixelChecksum() value. The _findchecksum UDF is written below. You must save thiscode as findchecksum_UDF.au3 and place it in C:\Program Files\AutoIt3\Include(or the Include folder wherever your AutoIt3 installation resides if it is not locatedin C:\Program Files) or the directory in which you will later save Example 10 in

AutoIt v3: Your Quick Guide 23

Page 24: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

order to create and run it. The _findchecksum() function returns 0 if the checksumis not found or returns an array containing x and y coordinates ([0] being x and[1] being y) if the checksum is found.

The _findpixelchecksum UDF is well suited for automating tasks where imagesmust be clicked or moved. A very popular field for this type of automation is videogame modification. There are many online role-playing games for which peopleprogram scripts like this in order to automate crafting, experience “grinding,” andother sorts of repetitive tasks.; ===================================================================================; _findchecksum UDF v1 - June 24, 2007; Written by Andy Flesner; Designed and Tested for Windows XP Service Pack 2; http://autoit.flesner.com; ===================================================================================#csSyntax is as follows: _findchecksum($checksum, $width, $height, $pcolor, $x = 0, _$y = 0, $d_width = @DesktopWidth, $d_height = @DesktopHeight)

$checksum - the checksum to search for$width - the width of the checksum area$height - the height of the checksum area$pcolor - the pixel color of the top left pixel of the checksum object$x - the starting x coordinate$y - the starting y coordinate$D_Width - Width of the total search area, default is desktop resolution width$D_Height - Height of the total search area, default is desktop resolution height

The function returns the x and y coordinates of the upper left corner wherethe checksum is found as an array. For Example:

$coordinates = _findchecksum($checksum, $width, $height, $pcolor)

The x coordinate would be $coordinates[0] and the y coordinate would be$coordinates[1].

If the coordinates are not found, the function returns a value of 0.#ce; ===================================================================================

Func _findchecksum($checksum, $width, $height, $pcolor, $x= 0, $y = 0, _$d_width = @DesktopWidth, $d_height = @DesktopHeight) $current_y = $d_height - 1 While 1

$xy = PixelSearch($x, $y, $d_width- 1, $current_y, $pcolor)If @error AND $current_y = ($d_height - 1) Then Return 0

AutoIt v3: Your Quick Guide 24

Page 25: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

ElseIf @error Then$x = 0$y = $current_y + 1$current_y = ($d_height - 1)ElseIf $checksum = PixelCheckSum($xy[0], $xy[1],$xy[0] + $width, _$xy[1] + $height) ThenReturn $xyElse$x = $xy[0] + 1$y = $xy[1]$current_y = $yEndIf WEndEndFunc

Example 10 selects an area, finds its checksum, and then finds that checksum onthe screen when a hotkey is pressed.

Example 10. findchecksum() User-Defined Function

#include <findchecksum_UDF.au3>

Global $checksum, $coord,$pcolor

;Specify checksum widthGlobal $width = 30;Specify checksum heightGlobal $height = 30

HotKeySet("{ENTER}","checksum_record")

Global $instructions1 = "Move the mouse to the top left of the search" & @LF & _"area and then press Enter to record the area."Global $instructions2 = "Press the F key to find the recorded area."

While $checksum ="" $coord = MouseGetPos()$pcolor = PixelGetColor($coord[0],$coord[1])ToolTip($instructions1 & @LF & @LF & "x = " & $coord[0] & @LF & "y = " & _$coord[1] & @LF & @LF & "Decimal Pixel Color = " & $pcolor,$coord[0] - 250, _$coord[1] - 100)Sleep(100)WEnd

HotKeySet("f","checksum_find")

While 1 ToolTip($instructions2) Sleep(100)

AutoIt v3: Your Quick Guide 25

Page 26: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

WEnd

Func checksum_record() $checksum = PixelChecksum($coord[0], $coord[1], $coord[0] + $width, _ $coord[1] + $height) HotKeySet("{ENTER}")EndFunc

Func checksum_find() ToolTip("") $found = _findchecksum($checksum, $width, $height,$pcolor) If$found = 0 ThenMsgBox(4096,"Error","Checksum not found.")ExitElseMouseMove($found[0] + ($width / 2), $found[1] + ($height / 2), 1000)ToolTip("Found it!")Sleep(5000)ToolTip("")MsgBox(0,"Checksum Found", "Checksum found with center at x=" &_$found[0] + ($width / 2) & " y=" & $found[1] + ($height / 2)& ".")Exit EndIfEndFunc

Run, or compile and run, Example 10. Then move your mouse cursor to an areaon the screen that you would like the program to find, and press Enter. Then moveyour cursor to a different point on the screen. By pressing the F key, you prove theconcept of the program and the cursor moves to the center of the checksum thatyou told it to store in memory (by pressing Enter earlier). See Figure 6 for anillustration.

Figure 6. Example 10 findchecksum() User-Defined Function Tooltips

AutoIt v3: Your Quick Guide 26

Page 27: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Conditional and Loop StatementsConditional and loop statements simplify source code and make complex taskspossible.

Instead of repeating the same code over and over, you can simply perform a loopstatement to repeat the code until a condition is met. While an expression is true,your statement will continuously loop.

Conditional statements allow you to perform tasks based on the truth of a givenexpression. If the given expression is true, the statement runs.

Conditional StatementsA conditional statement performs actions based on whether certain conditions aremet. There are three types of conditional statements in AutoIt:

1. If...Then...Else. If statements simply perform actions if an expression is true;otherwise, they perform actions listed after Else.In the following example, themessage box only pops up if $numberequals 2; if not, the script exits:

Global $number = 2 If $number = 2 Then MsgBox(0, "Message", "The value of $number is " & $number & ".") Else Exit EndIf

If statements can also be nested. This means that an If statement can containmultiple If statements within itself, as shown in the following example:

Global $number = 2 If @OSVersion = "WIN_XP" Then If @Username = "Administrator" Then If $number = "2" Then MsgBox(0, "Message", "The value of $number is " & $number & ".") Else Exit EndIf Else MsgBox(4096, "Error", "You must be logged on as Administrator.") EndIf Else MsgBox(4096, "Error", "You must be running Windows XP.") EndIf

ElseIf is used to add another expression to evaluate. Usually, aSelect...Case or Switch...Case statement is more effective for evaluatingmultiple expressions. The following example displays an If statement thatuses ElseIf:

AutoIt v3: Your Quick Guide 27

Page 28: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

If @OSVersion = "WIN_VISTA" Then MsgBox(0, "OS Version", "You are running Windows Vista.") ElseIf @OSVersion = "WIN_2003" Then MsgBox(0, "OS Version", "You are running Windows 2003.") ElseIf @OSVersion = "WIN_XP" Then MsgBox(0, "OS Version", "You are running Windows XP.") ElseIf @OSVersion = "WIN_2000" Then MsgBox(0, "OS Version", "You are running Windows 2000.") Else EndIf

Boolean (AND, OR, NOT) and logical (<,<=, >, >=, <>, =, ==) operators canbe used in Ifstatements. Here is an example that uses both Boolean and logicaloperators:

Global $num1 = InputBox("Number 1","Number 1: ","") Global $num2 = InputBox("Number 2","Number 2: ","") If @OSVersion = "WIN_XP" AND @OSServicePack = "Service Pack 2" Then If $num1 + $num2 > 10 Then MsgBox(0,"Greater than 10","The sum of Number 1 and Number 2 is " & _ "greater than 10.") ElseIf $num1 + $num2 < 10 Then MsgBox(0,"Less than 10","The sum of Number 1 and Number 2 is less " & _ "than 10.") Else MsgBox(0,"Must be 10","If not less than or greater than 10, thesum " & _ "of Number 1 and Number 2 must be equal to 10.") EndIf Else MsgBox(4096,"Error","You must be running Windows XP SP2.") EndIf

If the version of Windows on the user’s machine is not XP Service Pack 2, theuser sees a pop up telling him he must be running Windows XP SP2. If theuser is running XP SP2, the script performs an If statement on the $num1 +$num2 expression. If the expression is greater or less than 10, the user sees amessage box stating this. If neither of the expressions is true, the sum mustbe 10, and the user is prompted with a message stating this fact.

2. Select...Case. In the case of an If statement,an expression is evaluated as trueor false. If the expression is true, the statement associated with the expressionis executed. A Select...Case statement is similar, but instead of evaluatingan expression as true or false,it evaluates multiple expressions at once. Anexample of a Select...Case statement follows:

Select Case @OSVersion = "WIN_VISTA" MsgBox(0, "OS Version", "You are running Windows Vista.")

AutoIt v3: Your Quick Guide 28

Page 29: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Case @OSVersion = "WIN_2003" MsgBox(0, "OS Version", "You are running Windows 2003.") Case @OSVersion = "WIN_XP" MsgBox(0, "OS Version", "You are running Windows XP.") Case @OSVersion = "WIN_2000" MsgBox(0, "OS Version", "You are running Windows 2000.") EndSelect

A message box tells the user whether the version of Windows running is Vista,2003, XP, or 2000.

As with If statements, Select...Case statements can be nested and allow theuse of Boolean and logical operators. Instead of Else (as in If statements),these statements use Case Else, which performs the same task. Case Else runsif no other case succeeds as true. The following is an example of a nestedSelect...Case statement that uses Boolean and logical operators:

Global $num1 = InputBox("Number 1","Number 1: ","") Global $num2 = InputBox("Number 2","Number 2: ","")

Select Case @OSVersion = "WIN_XP" AND @OSServicePack = "Service Pack 2" Select Case $num1 + $num2 > 10 MsgBox(0,"Greater than 10","The sum of Number 1 and Number2 " & _ "is greater than 10.") Case $num1 + $num2 < 10 MsgBox(0,"Less than 10","The sum of Number 1 and Number2 is " & _ "less than 10.") Case $num1 + $num2 = 10 MsgBox(0,"Equals 10","The sum of Number 1 and Number 2 is " & _ "equal to 10.") EndSelect Case Else MsgBox(4096,"Error","You must be running Windows XP SP2.") EndSelect

3. Switch...Case. Switch...Case statements are very similar to Select...Casestatements; the difference is the layout of the expressions to be evaluated. Ina Switch...Case statement, the data to be evaluated is declared with Switch.The script then evaluates each case, just like a Select...Case statement, tosee which is true. (If none are true, the statement within Case Else is execu-ted.) One advantage of using Switch...Case is the To parameter, which allowsthe expression to be true if the value is between a range. Switch...Case state-ments can also be nested. The following is an example of a nestedSwitch...Case statement using the To parameter:

AutoIt v3: Your Quick Guide 29

Page 30: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Global $num1 = InputBox("Number 1","Number 1: ","") Global $num2 = InputBox("Number 2","Number 2: ","")

Switch @OSVersion Case "WIN_XP" Switch @OSServicePack Case "Service Pack 2" Switch $num1 + $num2 Case 0 To 9 MsgBox(0,"Less than 10","The sum of Number 1 and " & _ "Number 2 is less than 10.") Case 10 MsgBox(0,"Equals 10","The sum of Number 1 andNumber " & _ "2 is equal to 10.") Case Else MsgBox(0,"Greater than 10","The sum of Number1 and " & _ "Number 2 is greater than 10.") EndSwitch Case Else MsgBox(4096,"Error","You must be running Windows XPService " & _ "Pack 2.") EndSwitch Case Else MsgBox(4096,"Error","You must be running Windows XP.")EndSwitch

Loop StatementsLoop statements are just statements that repeat themselves a number of times.There are four types of loop statement available in AutoIt v3:

1. For...Next. The syntax for a For...Next loop statement is as follows:For <variable> = <start> To <stop> [Step <stepval>] Statements ...Next

A specified variable, which is automatically defined locally even if MustDeclareVars is enabled, is stepped to the stop number by <stepval> (default of 1).The loop is complete once the value of the variable exceeds the <stop> value.<stop> and <stepval> can be variables, but they are only read when the loopstarts for the first time. For...Next statements can be nested. The followingis an example of a For...Next statement in which the script displays a 10-second countdown, then pops up a message box that says, “Boom!”:

AutoIt v3: Your Quick Guide 30

Page 31: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

For $variable = 10 To 1 Step −1 SplashTextOn("Countdown",$variable,65,20) Sleep(1000) Next SplashOff() MsgBox(0,"", "Boom!")

2. For...In...Next. This type of loop statement is used to evaluate an array of dataor a COM object. This is the For...In...Nextsyntax:

For <variable> In <expression> Statements ...Next

If the expression is an object collection with no elements, the script skips theloop and the variable contains an empty string of data. If the expression isneither an object nor an array, the script ends with an error unless a customerror handler is used. For...In...Next statements can also be nested. Here isan example of using For...In...Next to evaluate an array of data:

Global $array[4]

$array[0]="w" $array[1]="x" $array[2]="y" $array[3]="z"

For $element IN $array MsgBox(0,"Current $array item",$element) Next

3. Do...Until. This type of loop performs its statements until an expression istrue. This is the Do...Until syntax:

Do Statements ... Until <expression>

The expression is tested after performing the statements, so the loop runs atleast once. Do...Until statements can also be nested. The following is an ex-ample that uses Do...Untilto perform a 10-second countdown and then popup a message:

$variable = 10

Do SplashTextOn("Countdown",$variable,65,20) Sleep(1000) $variable = $variable - 1

AutoIt v3: Your Quick Guide 31

Page 32: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Until $variable = 0

SplashOff() MsgBox(0,"","Boom!")

4. While...WEnd. While the expression is true, this loop continues executingdown to the WEnd statement. Unlike a Do...Untilstatement, a While loop’sexpression is evaluated at the beginning of the loop. This means that if theexpression is not true at the beginning of the loop, it does not run. TheWhile...WEnd syntax is as follows:

While <expression> Statements ... Wend

A continuous loop can be created using While...WEndif the expression is setto 1. This tells AutoIt to run the loop While 1=1. Continuous loops can beused to force the script to wait for some type of input (a hotkey being pressed,for instance).

The following is an example of a While...WEndstatement:$variable = 10

While $variable > 0 SplashTextOn("Countdown",$variable,65,20) Sleep(1000) $variable = $variable - 1 WEnd

SplashOff() MsgBox(0,"","Boom!")

While $variable is greater than zero, the loop continuously counts down from10 to 1 each second. After the loop is complete, a message box appears saying,“Boom!”

With...EndWithThis type of statement doesn’t really fit in as a conditional or loop statement. TheAutoIt help file categorizes With...EndWith statements as loop statements, but theironly use is to simplify object reference code. The syntax for a With...EndWithstatement is as follows:With <expression> Statements ... EndWith

AutoIt v3: Your Quick Guide 32

Page 33: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

The expression must be an object type. Example 11 and Example 12 show objectreference code that is simplified using the With...EndWith statement:

Example 11. Long Method Without Using With...EndWith

#csThe following script is written without using With...EndWith#ce

$object = ObjCreate("InternetExplorer.Application.1")

$object.Visible = 1$object.Height = 768$object.Width = 1024$object.Navigate("http://www.aismarthomes.com/")

Example 12. Simplified Code Using With...EndWith

#csThe following displays how With...EndWith statements simplify Object code#ce

$object = ObjCreate("InternetExplorer.Application.1")

With $object .Visible = 1 .Height = 768 .Width = 1024 .Navigate("http://www.aismarthomes.com/")EndWith

Notice how the $object is given to .Visible, .Height, .Width, and .Navigate au-tomatically within the With...EndWith statement. See Figure 7 for the results.

AutoIt v3: Your Quick Guide 33

Page 34: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Figure 7. Example 11 Long Method Without Using With...EndWith, and Example 12.Simplified Code Using With...EndWith—visible Internet Explorer window withdimensions of 1024×768

AutoIt v3: Your Quick Guide 34

Page 35: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Component Object Models (COM) ExtensionsCOM extensions provide a common interface for working with software appli-cations in a Microsoft environment. Applications have defined COM objects thatcan be used in AutoIt (and other programming languages) to manipulate theapplications and perform tasks within them. To use COM objects, you mustknow the object name and its properties and methods. To find an application’sobjects, and the object properties and methods, you can utilize Microsoft’sOLE/COM Object Viewer that is part of the Windows 2000 Resource Kit.You can download the OLE/COM Object Viewer here:

http://download.microsoft.com/download/win2000platform/oleview/1.00.0.1/nt5/en-us/oleview_setup.exe

You will likely receive an error about iviewers.dll when you run oleview.exe.To fix this error, download the following:

http://download.microsoft.com/download/2/f/1/2f15a59b-6cd7-467b-8ff2-f162c3932235/ovi386.exe

Once downloaded, run ovi386.exe and extract its contents to C:\MSTOOLS\BIN. Copy iviewers.dll from C:\MSTOOLS\BIN to the directory where youinstalled oleview_setup.exe. Then register the DLL using regsvr32iviewers.dll within the install directory of oleview_setup.exe.

When viewing objects within the OLE/COM Object Viewer, only those ob-jects with a TypeLib and an IDispatch control can be used within AutoIt.

The following is an example of using COM objects that simply creates an Excelspreadsheet and then closes Excel:

$oExcel = ObjCreate("Excel.Application") ; creates an Excel object

With $oExcel .Visible = 1 ; shows Excel .WorkBooks.Add ; creates a new workbook .Quit ; closes ExcelEndWith

For more detailed information about COM objects, please read the AutoIt v3help file.

Automation ExamplesWith its abilities to modify the registry, copy files, run as another user, controlkeyboard and mouse input, and use COM objects, there isn’t much you can’t do withAutoIt.

AutoIt v3: Your Quick Guide 35

Page 36: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

This section is full of examples modeled after scripts I have written and used as aserver systems administrator. All of these scripts were rewritten for this book; theyare designed and tested to work with Microsoft Windows XP Service Pack 2.

AntiVirus Compliance CheckThis program checks for the existing McAfee AntiVirus version, ePO Agent ver-sion, and the DAT definition file date. The script was designed to block users fromaccessing domain resources if they do not keep their systems AntiVirus compliant.It first detects a missing AntiVirus and/or an ePO Agent, then verifies that the DATdefinition file is within five business days old (McAfee does not usually releaseDAT files on weekends). Lock.exe is referenced in this script. It is listed later inthis guide as User Lockout. Example 13 uses nested If statements,Select...Case statements, and user-defined functions.

Example 13. AntiVirus Compliance Check

#include <Date.au3> ; Include Date constants

; Declare all Global Variables;=====================================================================Global $dat71, $dat71monthday, $dat71year, _ $dat71format, $dat80i, $dat80imonthday, _ $dat80iyear, $dat80iformat, $dat85, _ $dat85monthday, $dat85monthday, _ $dat85year, $dat85format, $datdate, _ $sLongDayName, $currentdate, $datediff, _ $answer, $username, $epoversion, _ $eporeg, $updatepath, $weekday

; Finds out who is currently logged onto the machine;=====================================================================$username = EnvGet("USERNAME")

; Pulls ePO Version from the Registry;=====================================================================$eporeg = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\ePolicy " & _"Orchestrator\Application Plugins\EPOAGENT3000","Version")

; Truncates the ePO Version to the leftmost 3 characters;=====================================================================$epoversion = StringLeft($eporeg,3)

If $epoversion = "3.6" Then ; Do NothingElseIf $epoversion = "" Then ; If the Agent key is missing, there is no Agent; installed RunWait("Lock.exe","") ; lock the account

AutoIt v3: Your Quick Guide 36

Page 37: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

MsgBox(0,"EPO Agent Not Installed!","You do not have a Virus-Scan Update " & _ "Agent installed! Your account has been locked out! Click OK to exit.") ExitElse ; If there is an Agent installed, but an outdated version RunWait("Lock.exe","") ; lock the account MsgBox(0,"EPO Agent Outdated!","You do not have a current Virus-ScanUpdate " & _ "Agent installed! Your account has been locked out! Click OK to exit.") ExitEndIf

; Runs the DatDate() function to determine the age of the installed DAT file;=====================================================================DatDate()

Func DatDate()

$dat71 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\ePolicy " & _ "Orchestrator\Application Plugins\VIRUSCAN7100","DatDate") ; pulls ; registry information for datdate for McAfee Scan Engine 7.1 $dat71monthday = StringTrimRight($dat71, 5) ; takes the month andday out of ; the datdate key $dat71year = StringTrimLeft($dat71, 6) ; takes the year out ofthe datdate key $dat71format = ($dat71year & "/" & $dat71monthday) ; reordersthe date with ; the year first YYYY/MM/DD format for later calculations

$dat80i = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\ePolicy " & _ Orchestrator\Application Plugins\VIRUSCAN8000","DatDate") ; pulls registry ; information for datdate for McAfee Scan Engine 8.0i $dat80imonthday = StringTrimRight($dat80i, 5) ; takes the month andday out of ; the datdate key $dat80iyear = StringTrimLeft($dat80i, 6) ; takes the year out ofthe datdate key $dat80iformat = ($dat80iyear & "/" & $dat80imonthday) ; reordersthe date with ; the year first YYYY/MM/DD format for later calculations

$dat85 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Network Associates\ePolicy " & _ Orchestrator\Application Plugins\VIRUSCAN8600","DatDate") ; pulls registry ; information for datdate for McAfee Scan Engine 8.5.0i $dat85monthday = StringTrimRight($dat85, 5) ; takes the month andday out of ; the datdate key $dat85year = StringTrimLeft($dat85, 6) ; takes the year out ofthe datdate key

AutoIt v3: Your Quick Guide 37

Page 38: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

$dat85format = ($dat85year & "/" & $dat85monthday) ; reorders thedate with ; the year first YYYY/MM/DD format for later calculations

If $dat71 = "" And $dat80i = "" And $dat85 = "" Then RunWait("Lock.exe","") ; lock the account MsgBox(0,"No Virus Protection Detected!","You are not currentlyrunning " & _ any anti-virus protection and your account has been locked out. Click " & _ "OK to close this message.") ElseIf $dat71 = "" And $dat80i = "" Then ; engine version is 8.5 $datdate = $dat85format ElseIf $dat71 = "" And $dat85 = "" Then ; engine version is 8.0i $datdate = $dat80iformat ElseIf $dat80i = "" And $dat85 = "" Then ; engine version is 7.1 $datdate = $dat71format Else EndIf

If FileExists("C:\Program Files\Network Associates\VirusScan\mcupdate.exe")Then $updatepath = "C:\Program Files\Network Associates\VirusScan\mcupdate.exe" ElseIf FileExists("C:\Program Files\McAfee\VirusScan Enterprise\mcupdate.exe") _ Then $updatepath = "C:\Program Files\McAfee\VirusScan Enterprise\mcupdate.exe" Else EndIf

$sLongDayName = _DateDayOfWeek( @WDAY ) ; converts the date intothe current ; day of the week for the Select...Case statement $currentdate = ( @YEAR & "/" & @MON & "/" & @MDAY ) ; piecestogether system ; variables to come up with the date in YYYY/MM/DD format $datediff = _DateDiff( 'd', $datdate, $currentdate) ; calculates the date ; difference between the current date and the DAT date

EndFunc

Select Case $sLongDayName = "Monday" $weekday = 2 Case $sLongDayName = "Tuesday" $weekday = 2 Case $sLongDayName = "Wednesday" $weekday = 2 Case $sLongDayName = "Thursday" $weekday = 2 Case $sLongDayName = "Friday" $weekday = 2

AutoIt v3: Your Quick Guide 38

Page 39: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Case $sLongDayName = "Saturday" $weekday = 0 Case $sLongDayName = "Sunday" $weekday = 1EndSelect

If $datediff >= (5 + $weekday) Then ; If the DAT is 5 business daysold or older If $username = "Administrator" Then ; pops up an error and closesthe script ; if Administrator is the logged in user MsgBox(0,"Anti-Virus Out of Date","Your are currently logged onto a " & _ "machine with out of date Anti-Virus. Click OK to exit.") Exit Else EndIf RunWait("Lock.exe","") ; locks the account $answer = MsgBox(4,"AntiVirus Warning","Your Anti-Virus definitionsare out " & _ "of date. Your account is now locked out and will remain locked out until " & _ "your Anti-Virus is up to date. Would you like to update now?") If $answer = 6 Then ; yes is clicked RunWait($updatepath) ; runs the Anti-Virus manual update DatDate() ; reruns the datdate checker to verify whether the DAT was ; successfully updated or not If $datediff >= (5 + $weekday) Then ; if the DAT is still5 business days ; or more old then pops up an error message MsgBox(0,"Error","Your update was unsuccessful. Click OK to exit.") Exit ElseIf $datediff < (5 + $weekday) Then ; if the DAT is nowless than 5 ; days old shows successful pop up MsgBox(0,"Update Successful","Your Anti-Virus was successfully " & _ "updated! Please click OK to exit.") Exit EndIf ElseIf $answer = 7 Then ; no is clicked MsgBox(0,"Warning","You have chosen NOT to update your Anti-Virus. " & _ "Your account will remain locked out until you do so.") EndIfElseEndIfExit

AutoPatcher FixThe script in Example 14 uses examples of FileCopy, WinWait, WinActive, WinActivate, WinClose, Run, and RunWait. The purpose of this program is to fix some DLL

AutoIt v3: Your Quick Guide 39

Page 40: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

registration problems with an old version of AutoPatcher—a free utility used toupdate Windows.

Example 14. AutoPatcher Fix

#NoTrayIcon ; Hides tray icon

; Run the Program;=====================================================================Run("C:\Program Files\AutoPatcher\Tools\AutoPatcher Module Editor.exe")

; Wait for the program to Open;=====================================================================WinWait("AutoPatcher Module Editor 2.0","")

; Check to see if the window is active, if not then make it active;=====================================================================If Not WinActive("AutoPatcher Module Editor 2.0","") Then _WinActivate("AutoPatcher Module Editor 2.0","")

; Wait for the program window to become the active window;=====================================================================WinWaitActive("AutoPatcher Module Editor 2.0","")

; Close the program window;=====================================================================WinClose("AutoPatcher Module Editor 2.0","")

; Copy all files necessary for the fix to C:\WINDOWS\system32 and Overwrite existing;=====================================================================FileCopy("C:\Program Files\AutoPatcher\bin\COMDLG32.OCX", _"C:\WINDOWS\system32\COMDLG32.OCX",1)FileCopy("C:\Program Files\AutoPatcher\bin\COMCTL32.OCX", _"C:\WINDOWS\system32\COMCTL32.OCX",1)FileCopy("C:\Program Files\AutoPatcher\bin\FM20.DLL","C:\WINDOWS\system32\FM20.DLL",1)FileCopy("C:\Program Files\AutoPatcher\bin\FM20ENU.DLL", _"C:\WINDOWS\system32\FM20ENU.DLL",1)FileCopy("C:\Program Files\AutoPatcher\bin\MSCOMCTL.OCX", _"C:\WINDOWS\system32\MSCOMCTL.OCX",1)FileCopy("C:\Program Files\AutoPatcher\bin\SSubTmr6.dll", _"C:\WINDOWS\system32\SSubTmr6.dll",1)FileCopy("C:\Program Files\AutoPatcher\bin\poweroff.exe", _"C:\WINDOWS\system32\poweroff.exe",1)

; Register all .ocx and .dll files with regsvr32.exe silently;=====================================================================RunWait('regsvr32 "c:\WINDOWS\system32\COMDLG32.OCX" /s')RunWait('regsvr32 "c:\WINDOWS\system32\COMCTL32.OCX" /s')RunWait('regsvr32 "c:\WINDOWS\system32\FM20.DLL" /s')

AutoIt v3: Your Quick Guide 40

Page 41: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

RunWait('regsvr32 "c:\WINDOWS\system32\FM20ENU.DLL" /s')RunWait('regsvr32 "c:\WINDOWS\system32\MSCOMCTL.OCX" /s')RunWait('regsvr32 "c:\WINDOWS\system32\SSubTmr6.dll" /s')

; Run the AutoPatcher program with the defaults.ini settings file in unattended mode;=====================================================================Run('C:\Program Files\AutoPatcher\AutoPatcher.exe /unattend:t2 /noeula " & _"/noreboot /skipdetection /defaults:C:\Program Files\AutoPatcher\defaults.ini')

Exit ; Exit the script

Change My Documents LocationThe program in Example 15 changes the location of the logged-in user’s MyDocuments short cut. This example uses keyboard presses and If statements.

Example 15. Change My Documents Location

#NoTrayIcon; Hides tray icon

; Declare Global Variables;=====================================================================Global $username, $newpath

$username = @UserName ; Detects username of current user

; Sets $homepath variable to desired location of My Documents;=====================================================================$newpath = InputBox("New My Docs Location","Please enter the new full pathfor " & _"your My Documents shortcut (a folder named after your username will be created " & _"here): “,"”)

; Check for the existence of $newpath and create it if it doesn’t already exist;=====================================================================If FileExists($newpath) ThenElse DirCreate($newpath)EndIf

; Open the My Documents Properties window with keyboard commands;=====================================================================Send("{LWINDOWN}d{LWINUP}")Sleep(500)Send("my{SPACE}d")Sleep(500)Send("{LSHIFT}+{F10}")Sleep(500)Send("{UP}{ENTER}")Sleep(500)

AutoIt v3: Your Quick Guide 41

Page 42: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

; Set the My Documents shortcut path to $newpath\$username;=====================================================================Send($newpath & "\" & $username)Send("{ENTER}")

; Wait 5 seconds for the Move Documents question to pop up, then answer No;=====================================================================WinWait("Move Documents","Would you like to move all",5)If WinExists("Move Documents","Would you like to move all") Then If Not WinActive("Move Documents","Would you like to move all") Then _ WinActivate("Move Documents","Would you like to move all") WinWaitActive("Move Documents","Would you like to move all") Send("n")ElseEndIf

; Wait 5 seconds for the Create Folder question to pop up, then answer No;=====================================================================WinWait("Create Folder","The folder",5)If WinExists("Create Folder","The folder") Then If Not WinActive("Create Folder","The folder") Then _ WinActivate("Create Folder","The folder") WinWaitActive("Create Folder","The folder") Send("n")ElseEndIfExit

Figure 8 shows the results.

Data Execution Prevention—DisableWritten to disable DEP in Windows XP, the script in Example 16 reruns itself asthe local Administrator, and then rewrites the boot.ini configuration file.

Figure 8. Prompt from Example 15.Change My Documents Location

AutoIt v3: Your Quick Guide 42

Page 43: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Example 16. Data Execution Prevention—Disable

#NoTrayIcon ; Hides tray icon

; Declare Global Variables;=====================================================================Global $admin, $password

$admin = "Administrator"$password = "password"

; The following IF statement forces the script to rerun itself as the Administrator;=====================================================================If Not $CMDLINE[0] Then RunAsSet($admin, @Computername, $password) If @Compiled Then RunWait('"' & @ScriptFullPath & '" /admin') Else RunWait('"' & @AutoItExe & '" "' & @ScriptFullPath & '" /admin') EndIf RunAsSet()ElseIf $CMDLINE[0] And $CMDLINE[1] = '/admin' Then FileSetAttrib("C:\boot.ini","-R") ; removes the Read-Only attributefrom boot.ini FileDelete("C:\boot.ini") ; deletes the original boot.ini IniWrite("C:\boot.ini","boot loader","timeout","30") ; writes first lineof new ; boot.ini IniWrite("C:\boot.ini","boot loader","default", _ "multi(0)disk(0)rdisk(0)partition(1)\WINDOWS") _ ; writes second line of new boot.ini IniWrite("C:\boot.ini","operating systems","multi(0)disk(0)rdisk(0)" & _ "partition(1)\WINDOWS",'"Microsoft Windows XP Professional" /fastdetect " & _ "/NoExecute=OptIn') _ ; writes final line of new boot.ini including the /NoExecute=OptIn switch to ; disable DEP FileSetAttrib("C:\boot.ini","+RH") ; sets attributes on new boot.ini file to ; Read-Only and HiddenEndIf

Outlook XP Preview Pane—DisableThe short and simple script in Example 17 writes a registry key that disables theOutlook Preview Pane in Outlook XP.

Example 17. Outlook XP Preview Pane—Disable

#NoTrayIcon ; Hides tray icon

; Writes registry key to disable the Outlook Preview Pane in OfficeXP;=====================================================================

AutoIt v3: Your Quick Guide 43

Page 44: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

RegWrite("HKEY_CLASSES_ROOT\CLSID\{00020D75-0000-0000-C000-000000000046}" & _"\Shell\Open\Command","","REG_SZ",'"C:\PROGRA~1\MICROS~2\Office10\OUTLOOK.EXE"' & _'/nopreview')

Enable Remote Desktop Connection and NetMeetingHere is another example of a script that reruns itself as the local Administrator.Example 18 enables Remote Desktop Connections and NetMeeting on the localmachine.

Example 18. Enable Remote Desktop Connection and NetMeeting

#NoTrayIcon ; Hides tray icon

; Declare Global Variables;=====================================================================Global $admin, $password

$admin = "Administrator"$password = "password"

; The following IF statement forces the script to rerun itself as the Administrator;=====================================================================If Not $CMDLINE[0] Then RunAsSet($admin, @Computername, $password) If @Compiled Then RunWait('"' & @ScriptFullPath & '" /admin') Else RunWait('"' & @AutoItExe & '" "' & @ScriptFullPath & '" /admin') EndIf RunAsSet()ElseIf $CMDLINE[0] And $CMDLINE[1] = '/admin' Then RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal " & _ "Server","fDenyTSConnections","REG_DWORD",0) ; writes value to enable RDP RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Conferencing\Mcpt", _ "Fpx","REG_BINARY","01000000") ; writes value to enable NetmeetingEndIf

Microsoft Windows XP Update VerifierThe program in Example 19 checks for the existence of various critical WindowsXP Post-SP2 updates since August 2006. It only runs on Windows XP SP2; anyother operating system forces the program to exit. For the May 2007 Internet Ex-plorer 6 patch, the script only installs the update if IE6 is detected on the machine.This example does not include every critical security patch since August 2006.Lock.exe is referenced in this script;it is listed later in this guide as User Lockout.

Example 19. Microsoft Windows XP Update Verifier

#NoTrayIcon ; Hides tray icon

AutoIt v3: Your Quick Guide 44

Page 45: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

;Restricts to English - United States Operating Systems;=================================================================If Not (@OSLang = "0409") Then ExitEndIf

; If not Win_XP then Exit;=================================================================If @OSVersion <> "Win_XP" Then ExitEndIf

;If the computer is the following machine, don’t run this script;=================================================================If @ComputerName = "Computer" Then ExitEndIf

;Global Variables not related to XP or 2K specifically;=================================================================Global $ieversion = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\" & _"Internet Explorer","Version")

;Global Variables for XP Patches;=================================================================;August 2006 UpdatesGlobal $XPKB921883,$XPKB920214,$XPKB920670,$XPKB920683,$XPKB921398, _$XPKB922616,$XPKB918899

;September 2006 UpdatesGlobal $XPKB919007,$XPKB920685,$XPKB925486

;October 2006 UpdatesGlobal $XPKB922819,$XPKB923191,$XPKB923414,$XPKB924191,$XPKB924496

;November 2006 UpdatesGlobal $XPKB920213, $XPKB924270

;January 2007 UpdatesGlobal $XPKB926255

;February 2007 UpdatesGlobal $XPKB928843,$XPKB926436,$XPKB924667,$XPKB918118

;April 2007 UpdatesGlobal $XPKB925902, $XPKB930178, $XPKB931261, $XPKB931784, $XPKB932168

;May 2007 UpdatesGlobal $XPKB931768

AutoIt v3: Your Quick Guide 45

Page 46: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

; Check for WinXP SP2;=================================================================If @OSServicePack = "Service Pack 2" Then WinXPUpdate()Else MsgBox(48,"Error","Your System is not running Windows XP Service Pack 2.") RunWait("lock.exe","") ExitEndIf

;Windows XP Patch check routine;===============================Func WinXPUpdate()

;August 2006 Updates $XPKB920214 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB920214","Description") $XPKB920670 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB920670","Description") $XPKB920683 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB920683","Description") $XPKB921398 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB921398","Description") $XPKB922616 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB922616","Description")

If $XPKB920214 = "" Or $XPKB920670 = "" Or $XPKB920683 = "" Or$XPKB921398 = "" _ Or $XPKB922616 = "" Then Lock() EndIf

;September 2006 Updates ;================== $XPKB919007 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB919007","Description") $XPKB920685 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB920685","Description") $XPKB925486 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB925486","Description")

If $XPKB919007 = "" Or $XPKB920685 = "" Then

AutoIt v3: Your Quick Guide 46

Page 47: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Lock() EndIf

;October 2006 Updates ;================ $XPKB922819 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB922819","Description") $XPKB923191 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB923191","Description") $XPKB923414 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB923414","Description") $XPKB924191 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB924191","Description") $XPKB924496 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB924496","Description")

If $XPKB922819 = "" Or $XPKB923191 = "" Or $XPKB923414 = "" Or$XPKB924191 = "" _ Or $XPKB924496 = "" Then Lock() EndIf

;November 2006 Updates ;================ $XPKB920213 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB920213","Description") $XPKB924270 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB924270","Description")

If $XPKB920213 = "" Or $XPKB924270 = "" Then Lock() EndIf

;January 2007 Updates ;================ $XPKB926255 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB926255","Description")

If $XPKB926255 = "" Then Lock() EndIf

AutoIt v3: Your Quick Guide 47

Page 48: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

;February 2007 Updates ;================ $XPKB928843 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB928843","Description") $XPKB926436 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB926436","Description") $XPKB924667 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB924667","Description") $XPKB918118 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB918118","Description")

If $XPKB928843 = "" Or $XPKB926436 = "" Or $XPKB924667 = "" Or$XPKB918118 = "" _ Then Lock() EndIf

;April 2007 Updates ;================ $XPKB925902 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB925902","Description") $XPKB930178 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB930178","Description") $XPKB931261 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB931261","Description") $XPKB931784 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB931784","Description") $XPKB932168 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB932168","Description")

If $XPKB925902 = "" Or $XPKB930178 = "" Or $XPKB931261 = "" Or$XPKB931784 = "" _ Or $XPKB932168 = "" Then Lock() EndIf

;May 2007 Updates ;================ $XPKB931768 = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows " & _ "XP\SP3\KB931768","Description")

AutoIt v3: Your Quick Guide 48

Page 49: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

If $XPKB931768 = "" Then If StringLeft($ieversion,1) = "6" Then Lock() Else EndIf EndIf

EndFunc

;=====================================================================;Prompt and Lockout Function to notify users they are not updated;=====================================================================

Func Lock() RunWait("lock.exe","") Sleep(2000) MsgBox(48,"Attention!","You are missing Microsoft Windows XP Critical " & _ "Security Patches, please install them.") ExitEndFunc

Proxy Server Detector for Internet ExplorerThe program in Example 20 pings proxy servers and sets Internet Explorer to usethe first proxy that it can ping successfully. Replace “proxy1,” “proxy2,” “proxy3,”etc. with valid proxy server IP addresses, and replace “portnumber” with a validport number for the respective proxy server.

Example 20. Proxy Server Detector for Internet Explorer

#NoTrayIcon ; Hides tray icon

; Ping first proxy server then set it if pingable;=====================================================================If Ping("proxy1") Then RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyEnable","REG_DWORD",1) RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyServer","REG_SZ","proxy1:portnumber") RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyOverride","REG_SZ","<local>")

; Ping second proxy server then set it if pingable;=====================================================================ElseIf Ping("proxy2") Then RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyEnable","REG_DWORD",1) RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyServer","REG_SZ","proxy2:portnumber")

AutoIt v3: Your Quick Guide 49

Page 50: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyOverride","REG_SZ","<local>")

; Ping third proxy server then set it if pingable;=====================================================================ElseIf Ping("proxy3") Then RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyEnable","REG_DWORD",1) RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyServer","REG_SZ","proxy3:portnumber") RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyOverride","REG_SZ","<local>")

; Ping fourth proxy server then set it if pingable;=====================================================================ElseIf Ping("proxy4") Then RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyEnable","REG_DWORD",1) RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyServer","REG_SZ","proxy4:portnumber") RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyOverride","REG_SZ","<local>")

; Disable proxy settings if no proxy server is reachable;=====================================================================Else RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\" & _ "Internet Settings","ProxyEnable","REG_DWORD",0)EndIf

Run("C:\Program Files\Internet Explorer\IEXPLORE.EXE") ; Run Internet Explorer

User LockoutExample 21 uses a purposely failed network drive mapping to the C$ admin shareon the local machine repeatedly to lock out a user’s account. You can use a localor domain account, but you must set the loop count above the lockout thresholdas set by your group policy or local security policy.

Example 21. User Lockout

#NoTrayIcon ; Hides tray icon

If @UserName = "Administrator" Then Exit; ElseIf @UserName = “user” Then ; Exit

AutoIt v3: Your Quick Guide 50

Page 51: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

Else LockAcct() ; run the lockout function if the user is not exemptEndIf

Func LockAcct() $i = 0 While $i < 4 ; loops 4 times to lockout the current user’s account RunWait(@ComSpec & " /c " & "net use * \\127.0.0.1\C$ BadPassword " & _ "/USER:DOMAIN\%USERNAME%","",@SW_HIDE) $i = $i + 1 WEndEndFunc

User SID LookupWritten to solve the issue of finding a user’s SID in Windows, this utility can finda SID on the local machine or on a domain. Example 22 uses COM objects aswell as the A3LSecurity.au3 include from the Auto3Lib UDF library mentionedearlier in this Short Cut.

Example 22. User SID Lookup

#NoTrayIcon ; Hides tray icon#include <A3LSecurity.au3>

Opt("MustDeclareVars", 1)

Global $sUser, $aName

$sUser = InputBox("SID Lookup", "Enter UserName:", "", "", 200, 130)

If @Error <> 0 Then Exit

$aName = _Security_LookupAccountName($sUser)If @Error = 0 Then MsgBox(0,"SID Lookup","SID .....: " & $aName[0] & @CR & _ "Domain ..: " & $aName[1] & @CR & _ "SID Type : " & _Security_SidTypeStr($aName[2]))Else MsgBox(0,"SID Lookup","Invalid user name")EndIf

Figure 9 shows the results.

Word Document Title ChangerThis program was written using the Microsoft Word Automation Library men-tioned earlier in the user-defined functions section. The script in Example 23

AutoIt v3: Your Quick Guide 51

Page 52: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

scours a directory for *.doc files, and then sets the Title property of each file to itsfilename while keeping modified dates intact.

Example 23. Word Document Title Changer

#NoTrayIcon ; Hides tray icon

; Include File, Word, and GUI Constants;=====================================================================#include <file.au3>#include <Word.au3>#include <GuiConstants.au3>

; Change to OnEvent Mode;=====================================================================Opt('GUIOnEventMode', 1)

; Declare Global Variables;=====================================================================Global $LogPath, $DocPath, $progress, $progresspercent

; GUIGUICreate("Microsoft Word Document Title Changer", 320, 250)GUISetIcon("icon.ico")GUISetOnEvent($GUI_EVENT_CLOSE, 'Event_GUIClose')

; PICGUICtrlCreatePic("logo.gif", 128.5, 5, 63, 56)

; Log PathGUICtrlCreateLabel("Please type the full path where you would", 10, 70, 300, 15, _$SS_CENTER)GUICtrlCreateLabel("like to save the log file:", 10, 85, 300, 15, $SS_CENTER)$LogPath = GUICtrlCreateInput("", 10, 105, 300, 20)

; Modification PathGUICtrlCreateLabel("Please type the full path of the directory", 10, 130, 300, 15, _$SS_CENTER)GUICtrlCreateLabel("you would like files changed in:", 10, 145, 300, 15, $SS_CENTER)$DocPath = GUICtrlCreateInput("", 10, 165, 300, 20)

Figure 9. Prompt from Example 22.User SID Lookup

AutoIt v3: Your Quick Guide 52

Page 53: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

; ButtonGUICtrlCreateButton("Go!", 45, 200, 230, 30)GUICtrlSetOnEvent(−1, 'TitleChange')

GUISetState(@SW_SHOW) ; show the GUI

While 1 Sleep(250)WEnd

Func TitleChange() ; Hide the GUI while the function is running ;===================================================================== GUISetState(@SW_HIDE)

_WordErrorHandlerRegister()

; Opens Word ;===================================================================== $oWordApp = _WordCreate("", 0, 0, 0)

; Creates $sDocPath variable based on the entry in the GUI for the Change path ;===================================================================== $sDocPath = GUICtrlRead($DocPath)

; Adds trailing backslash if it doesn’t exist ;===================================================================== If StringRight($sDocPath, 1) <> "\" Then $sDocPath &= "\" EndIf $logpathfirst = GUICtrlRead($LogPath) If StringRight($logpathfirst, 1) <> "\" Then $logpathfirst &= "\" EndIf

; Creates $sLogPath variable based on the entry in the GUI for the Log path ;===================================================================== $sLogPath = $logpathfirst & "wordtitle.log"

; Pulls the filenames of all files in the Change directory ;===================================================================== $search = FileFindFirstFile($sDocPath & "*.doc") $filelist = _FileListToArray($sDocPath,"*.doc",1)

; Calculates the percentage change of each doc file toward the total number ;===================================================================== $filepercent = 100 / $filelist[0]

; Check if the search for *.doc was successful

AutoIt v3: Your Quick Guide 53

Page 54: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

;===================================================================== If $search = −1 Then MsgBox(0, "Error", "No files/directories matched the search pattern") Exit EndIf

; Opens the log file for writing ;===================================================================== FileOpen($sLogPath, 1)

; Turns on the Progress Bar ;===================================================================== ProgressOn("Doc Title Change Progress","Word Document titles " & _ "changing...","",300,200,16)

While 1 ; loops until there are no more *.doc files $file = FileFindNextFile($search) If @error Then ; if the last file listed was not *.doc then theloop exits ProgressOff() ; turns off progress bar ExitLoop ; exits the While...WEnd statement Else EndIf $filetime = FileGetTime($sDocPath & $file,0,1) ; pulls theModified Date ; from file properties $oDoc = _WordDocOpen($oWordApp, $sDocPath & $file) ; opensthe last found ; *.doc file $sTitle = _WordDocPropertyGet($oDoc, "Title") ; gets originaltitle of Word ; Doc ; Writes the old title to the log file ;===================================================================== FileWriteLine($sLogPath, "===========================") FileWriteLine($sLogPath, $sDocPath & $file) FileWriteLine($sLogPath, "===========================") FileWriteLine($sLogPath, "Old Title was: " & $sTitle) ; Creates $sFileName variable based on the filename and removes the trailing ; .doc ;===================================================================== $sFileName = StringTrimRight($file, StringLen($file) -StringInStr($file, _ ".", Default, −1) + 1) _WordDocPropertySet($oDoc, "Title", $sFileName) ; sets new titleto $sFileName $sTitleNew = _WordDocPropertyGet($oDoc, “Title”) ; gets new titlefor Log ; Write the new title and the modification date to the log file ;=====================================================================

AutoIt v3: Your Quick Guide 54

Page 55: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

FileWriteLine($sLogPath, “New Title is: " & $sTitleNew) FileWriteLine($sLogPath, “Modification Date: " & $filetime) FileWriteLine($sLogPath, "") FileWriteLine($sLogPath, "") _WordDocClose($oDoc, −1) ; closes the Word doc saving changes made FileSetTime($sDocPath & $file,$filetime,0) ; sets themodification date back ; to the original time/date $progress = $progress + $filepercent ; adds the percentage change of ; completing one file to the progress bar $progresspercent = StringLeft($progress,2) ; trims the percentageto 2 ; characters ProgressSet($progress,$progresspercent & " % completed..."); sets the ; progress bar to the current completion % WEnd

FileClose($sLogPath) ; Closes log file FileClose($search) ; Closes the search handle _WordQuit($oWordApp) ; Closes MS Word MsgBox(0,"Completed","All Word Documents in " & $sDocPath & " havehad their " & _ "titles changed to their corresponding filenames. The modification dates on " & _ "the files have remained intact.") ExitEndFunc

; Closes the GUI if the X button is pressed to exit;=====================================================================Func Event_GUIClose() ExitEndFunc

Figure 10 shows the results.

ConclusionBy reading this guide to AutoIt v3, you have learned about variables and includes,graphical user interfaces, user functions, and conditional and loop statements. Thesections and examples have given you the foundation for building any programpossible in the AutoIt language. The final section of this Short Cut has providedautomation examples that apply its teachings in real world environments. Manyof these examples can be used by system administrators or can be modified andused for other purposes. AutoIt v3: Your Quick Guide is designed to be a continualreference for you as you develop your skills as an AutoIt programmer.

AutoIt v3: Your Quick Guide 55

Page 56: AutoIt v3: Your Quick Guide · AutoIt source code was completely rewritten in C++ and development stalled until 2003, when the first beta version of AutoIt v3 was released. Over 100

You should now be confident in your ability to conquer any automation task beforeyou.

Figure 10. Prompt from Example 23.Word Document Title Changer

AutoIt v3: Your Quick Guide 56