Useful AutoIt Scriptlets

Trackback or

There are a number of things that you can do with AutoIt that only take a few lines of code. I’ve decided to put a number of these into a some really quick scriptlets that you can then use to augment your scripts.

Determine Drive or Network Share

This script determines whether it is being run from a local drive or a network share. It will then display that drive or share.

Dim $LocationType
Dim $Location
 
If StringMid(@ScriptDir,2,1)=":" Then
	$LocationType = "Drive"
Else
	$LocationType = "Network"
EndIf
 
Switch $LocationType
	Case "Drive"
		$Location = StringLeft(@ScriptDir,2)
	Case "Network"
		$Location = StringLeft(@ScriptDir,StringInStr(@ScriptDir,"\",-1,4))
EndSwitch
 
MsgBox(0,$LocationType,$Location)

Download this code: RunFrom.au3

Replace Text in File

Use this code to replace every instance of a text string in a text file with a different text string.

$TextFileName = "TextFile.txt"
$FindText = "dog"
$ReplaceText = "cat"
 
$FileContents = FileRead($TextFileName)
$FileContents = StringReplace($FileContents,$FindText,$ReplaceText)
FileDelete($TextFileName)
FileWrite($TextFileName,$FileContents)

Download this code: ReplaceText.au3

Internet File Downloader

You can generate your own custom download progress bar with this script.

$FileURL = "http://www.DailyCupOfTech.com/Downloads/TorparkSetup.exe"
$FileName = "TorparkSetup.exe"
$FileSaveLocation = FileSaveDialog("Save Location...",@ScriptDir,"All (*.*)",18,$FileName)
$FileSize = InetGetSize($FileURL)
 
InetGet($FileURL,$FileName,0,1)
 
ProgressOn("","")
While @InetGetActive
	$Percentage = @InetGetBytesRead * 100 / $FileSize
	ProgressSet($Percentage,"Downloaded " & @InetGetBytesRead & " of " & $FileSize & " bytes","Downloading " & $FileName)
	Sleep(250)
Wend
ProgressOff()
 
MsgBox(0, "Done","Download Complete!")

Download this code: FileDownloader.au3

Create a Shortcut

This script creates a shortcut on the desktop to notepad.

$FileName = "C:\Windows\Notepad.exe"
$LinkFileName = @DesktopDir & "\Text Editor.lnk"
$WorkingDirectory = @DesktopDir
$Icon = "C:\Windows\system32\SHELL32.dll"
$IconNumber = 57
$Description = "This is the text editor that comes with Windows"
$State = @SW_SHOWMAXIMIZED ;Can also be @SW_SHOWNORMAL or @SW_SHOWMINNOACTIVE
 
FileCreateShortcut($FileName,$LinkFileName,$WorkingDirectory,"",$Description,$Icon,"",$IconNumber,$State)

Download this code: CreateShortcut.au3

Display Drive Information

Retrieve specific information about each of the drives connected to the system.

$DriveArray = DriveGetDrive("all")
If Not @error Then
	$DriveInfo = ""
    For $DriveCount = 1 to $DriveArray[0]
        $DriveInfo &= StringUpper($DriveArray[$DriveCount])
		$DriveInfo &= " -  File System = " & DriveGetFileSystem($DriveArray[$DriveCount])
		$DriveInfo &= ",  Label = " & DriveGetLabel($DriveArray[$DriveCount])
		$DriveInfo &= ",  Serial = " & DriveGetSerial($DriveArray[$DriveCount])
		$DriveInfo &= ",  Type = " &  DriveGetType($DriveArray[$DriveCount])
		$DriveInfo &= ",  Free Space = " & DriveSpaceFree($DriveArray[$DriveCount])
		$DriveInfo &= ",  Total Space = " & DriveSpaceTotal($DriveArray[$DriveCount])
		$DriveInfo &= ",  Status = " & DriveStatus($DriveArray[$DriveCount])
		$DriveInfo &= @CRLF
    Next
	MsgBox(4096,"Drive Info", $DriveInfo)
EndIf

Download this code: DriveInfo.au3

Determine If A Process is Running

Checks to see if a specific named process is running and indicates its status.

$ProcessName = "Notepad.exe"
 
If ProcessExists($ProcessName) Then
	MsgBox(0,"Running",$ProcessName & " is running.")
Else
	MsgBox(0,"Not Running",$ProcessName & " is not running.")
EndIf

Download this code: ProcessRunning.au3

Generate a Random Number

Generates a random number between two specified values.

$LowerLimit = 104
$UpperLimit = 213
 
$RandomNumber = Random($LowerLimit,$UpperLimit,1)
 
MsgBox(0,"Random Number",$RandomNumber)

Download this code: RandomNumber.au3

Count Up Timer

This script will count the seconds that have passed until a certain number has been reached.

SplashTextOn("Timer","0 Seconds",125,25)
 
$BeginTime = TimerInit()
$CountTo = 10
$SecondsLapsed = 0
 
While $SecondsLapsed<$CountTo
	$TimeDifference = TimerDiff($BeginTime)
	$SecondsLapsed = Round($TimeDifference/1000,0)
 
	ControlSetText("Timer", "", "Static1", $SecondsLapsed & " Seconds")
	Sleep(1000)
WEnd

Download this code: Timer.au3

Suggest More Scriptlets

I understand that this is just the tip of the iceberg when it comes to possible scriptlets. If you have any scriptlets of your own or any suggestions on some good scriptlets, just let me know and I will see what I can do.

Trackback link - http://www.dailycupoftech.com/useful-autoit-scriptlets/trackback/
Tim Fehlman

36 Responses to “Useful AutoIt Scriptlets”

  1. scott Says:

    I’m really wanting to get into AutoIt, but my biggest problem (besides never scripting anything beyond really basic .bat scripts) is that I don’t know what to create. I’ve thought of something but I don’t know if its possible. Is it possible to have a script that can change my screen resolution?

  2. Tim Fehlman Says:

    Absolutely! The bottom line for AutoIt is that if you can do it with a mouse and keyboard, you can do it with AutoIt! I know of at least two different ways that this can be done.

    Now, I would normally create this script and post it on the website but since you indicated a desire to learn AutoIt, I’m not going to do that. But rest assured that it is possible.

    If you are looking for a hint, seek and ye shall find! (Remember, the goal of scripting is to be able to automate a process, not necessarily re-invent the wheel!)

    Tim

  3. Dave Says:

    Hey
    I wrote a little script that gets the systems file information…like size and version info etc..is there a scriptlet or method for AutoIt that will compare two files….binary…or it this something best handled by an external application….??? its all part of a bigger project to track system changes on enduser systems.

  4. Tim Fehlman Says:

    Dave,
    Probably the easiest way to check for file changes on an end users system from the file level is to perform an MD5 hash on the file (see Perform MD5 Using AutoIt) and record it’s value. Then, run an MD5 on it again and compare it to the recorded value. If the file has changed, then the MD5 value will also have changed. This works really nicely because even if a file’s attributes, time stamps, and file size have not changed (two common ways of determining changes in files) the MD5 value will change.

    Hope that helps.

    Tim

  5. Dave Says:

    Thanx Tim
    Sounds like a viable soution…better than my idea…and most likely less overhead.
    Dave

  6. Brent Says:

    Tim,
    I’m trying to determine if a service, not a process, is running. If it’s not I would like to start the process. I’ve been unsuccessful doing so using your Process Scriptlet as an example. Can you point me in the right direction? Thanks –

  7. Tim Fehlman Says:

    Brent,
    Every service has a process in the background. What you need to determine is the name of the executable that is running. This can be determined by going to the services console and opening up the service. In the General tab, there will be a field called Path to executable. This is the name of the executable.

    To start that executable if it is not running, simple use the Run or RunWait command to execute the net start command for the service.

    That should at least point you in the right direction.

    Tim

  8. Hickman Says:

    I love autoit and have wrote hundreds of scripts. I am glad you are doing this site. I like the easy of which autoit can be used. VB and others have their places but they are generally so much over kill and syntax. Thanks again.

  9. Daily Cup of Tech Says:

    Submissions Thank You! Top 100 Torpark Installer Tracking Users, IP’s, and Computers Upgrade Ubuntu 6.06 to 6.10 USB Drive AutoRun.inf Tweaking USB Drive Menu System USB Drive Splash Screen USB Drive Systems Useful AutoIt Scriptlets Users Online Using a TrueCrypt Volume Windows Backup With Rsync and FreeNAS Windows Home Server Screenshot Tour Windows Update Without Windows Update Wish List Zen and the Art of the USB Drive Series

  10. Dave Says:

    HAHA! Hadn’t even considered using AutoIt to create desktop shortcuts (.LNK files).

    I’ve fought with other tools (makescut.exe for example) that can be a real pain.

    With this code, I can customize it any way I want. Use it as-is ready for a command line, or I can add logging, or reporting, or anything I want to the code.

    Great idea!

  11. Chuck Z Says:

    I have windows vista and outlook 2002. The problem I have is every time I open outlook I have to enter the password for every email address I am trying to receive from my esp.
    I have been told that this is a problem with outlook 2002 and vista. microsoft will not fix it. They want you to update to a later version of office.

    One of the forums i read said it would be possible to automate this repetive process with autoit. Can you help?

    Thanks, chuck

  12. IL12 Says:

    Another useful applet/script would be to take all files of a certain extension which you could edit the extension chosen, and select a directory, and have it move all of those files into a file/other directory of your choice.
    For example, to have all of your .exe, .msi, etc files moved into the same folder
    An added plus would be the ability to have it automatically compress the folder/directory once all of the files were moved.

  13. santosh Says:

    I love AutoIt and have wrote hundreds of scripts. I am glad you are doing this site. I like the easy of which AutoIt can be used. VB and others have their places but they are generally so much over kill and syntax. Thanks again.

  14. Rathnasekaran Says:

    Hi,

    Please help how to interact the menubars in lotusnotes 6.5 using Autoit

  15. Richard Says:

    Is there a program for this that records, mouse/keyboard presses and creates a script for it?

  16. Richard Says:

    It would be nice to have a script that loads the webpages from your favorite sites, so you don’t have to. Kind of like an RSS reader except for the internet.

  17. steve Says:

    Is there a problem with the links to the scripts on the server? I am getting the same error with 2 different browsers. Could not open script

  18. Tim Fehlman Says:

    Thanks, steve. Problem should now be solved.

    Tim

  19. Jay Says:

    Hi. I am rather new to using AutoIT and script writing in general and find the program very easy to understand. Nonetheless, there are still some obvious things I haven’t caught on to. I was wondering if there was a way to combine the file find scriplet mentioned above with an input box to serve a similar function such as a windows search (input file wanting to find and directory to look in). I realize I could simply use the search function, but I have more fun trying to understand how things work by having the whole thing and taking it apart to understand it. I hope that isn’t as confusing as I think it sounds. I hope someone can help me. Thank you

    Jay

  20. Mark Reinhart Says:

    I have program that is monitoring timeclocks. The program normally displays that the timeclocks are all “idle”. Once in a while, one or more of the timeclocks will loose communication. An error will show up indicating that communication has been lost and is trying to reconnect. Unfortunately, that seems to be the only indication that there is a problem. Is there a way for Autoit to constantly monitor a window for a particular word then beep. Or possibly just monitor a spot within a window for a change of color. I have monitored color spots on the entire screen, but not a location in a window.

  21. tek9 Says:

    Richard:
    Yes you can load multiple webpages look in the au3 helpfile for the shellexecute() function, or search google for autoit open a webpage.

    Jay: Yes, you’re looking for working with the inputbox() function to ask a user for information without actually building a GUI form.

    Mark: Ehhhh…kind of, but it’s not pretty. You can monitor a window to see if a string of text resides in it by using the WinGetText() function to get the window text, and StringInStr() to determine whether the string is actually there. You *could* check for a change of color in a specific window, but that would require a boat load of coding to get positions and having to deal with re-sizes, and the windows (all of them you are monitoring) would have to be visible on the screen, not just running in the background.

  22. tek9 Says:

    Richard: Prior about recording mouse clicks and keystrokes, yes. I recommend downloading SciTE for use in coding AU3 applications, under the tools menu you will see an AU3Recorder tool that will allow you to record this information

  23. Tutungzone Says:

    I have used AutoIT in the past, and am having a need for it again, but have forgotten how to do somethings with it, and it seems searches are coming up with nothing. I have a GUI interface I have written in AutoIT, and I want to add the functionality of a button click to watch in another GUI window an active log file. I have done this in the past, but cannot figure out what I did to open the txt file in another GUI screen and activly watch the txt file as it is added to. The text file is a log file created by another process that constantly writes to the file… so AutoIT would just be viewing the file as changes are made to the txt file… anyone do this before besides me? Shed some light please.

  24. R Says:

    How about a scriptlet that would format a size (in bytes) to a number and a unit, with a given number of decimals.

    e.g.

    FormatSize(12168) would return “11.9 KB”

  25. P00PDOG Says:

    I was curious….the count down timer code you have here, what version of Aotoit it it supposed to work with? I have the latest version i think 3.3.0.0 and a box shows up but no text. I tried to copy the code exactly and still no text.

  26. P00PDOG Says:

    DOH! nevermind, the size of the window was too small for the font that was being used. I never changed my font but maybe AutoIT did?

  27. robert Says:

    Im new to all of this and i have spent hrs getting nowhere and i was wondering how would get the mouse to move to specific areas not set areas tho, that depends on the color?

  28. John Thomas Says:

    I am absolutely new to AutoIT. I have a requirement to automate some manual application monitoring tasks. I will need to start an instance of the monitoring tool and send some key strokes or mouse inputs to get the monitoring tool working. I am pretty sure AutoIt can do this part. I would also want to read the output displayed in monitoring tool’s window and log it myself, say in a database, for later use. Will AutoIt help me achieve this?

  29. karthik Says:

    Pls send me a script that logs the system date into a .txt file in the background.

  30. robert Says:

    omm i was wondering how to search portions of the screen for a specif color im having trouble with it. i can search the whole screen but thats not what i want to do i just need to search portions of it for specific colors any help ?

  31. robert Says:

    Global $UnPaused
    HotKeySet(”1″, “TogglePause”)
    HotKeySet(”{ESC}”, “Terminate”)

    While 1
    Sleep(100)
    WEnd

    Func TogglePause()
    $UnPaused = NOT $UnPaused
    While $UnPaused
    MouseMove(151,87,(10))
    MouseMove(151,285,(10))
    MouseMove(355,285,(10))
    MouseMove(355,87,(10))
    MouseMove(151,87,(10))
    WEnd
    EndFunc

    Func Terminate()
    Exit 0
    EndFunc

    here is my code and i would like to know how i could pixel search just the given area

  32. engineer Says:

    for the internet file downloader

    I would rather suggest that u creat a msgbox that asks user to input the url

    great work anyways

  33. Ken Says:

    Robert there is a funtion in auto it already.

    PixelSearch ( left, top, right, bottom, color [, shade-variation [, step [, hwnd]]] )

    example
    ; Find a pure red pixel in the range 0,0-20,300
    $coord = PixelSearch( 0, 0, 20, 300, 0xFF0000 )
    If Not @error Then
    MsgBox(0, “X and Y are:”, $coord[0] & “,” & $coord[1])

    ps this is form the help file within the script editor that comes with autoit.
    EndIf

  34. Robert’s blog » Blog Archive » Useful AutoIt Scriptlets Says:

    […] http://www.dailycupoftech.com/useful-autoit-scriptlets/ […]

  35. Frank Says:

    Send keystrokes to any program

    Example batch file to automate print of PDF file

    start passkeys Reader “^p{ENTER}” “{ENTER} ^q”
    “C:\Program Files\Adobe\Acrobat 6.0\Reader\AcroRd32.exe” “F:\games.pdf”

    ;Autoit V3.3
    ;PASSKEYS.EXE FDH 24 NOV 2009
    ;
    ;syntax:
    ;passkeys programname “keys1″ “keys2″ “keys3″
    ;where keys is a string according to AUTOIT key format
    ;longer delay if control keys detected in command line
    ;10 second delay between keys1 and keys2 etc
    ; it may be slow but you dont have to be there

    global $LOGNAME = “C:\temp\logfile.txt”

    Opt(”SendKeyDelay”, 20) ;50 milliseconds
    Opt(”WinTitleMatchMode”, 2) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase

    DIM $keys[10]

    $FileLogging = True

    if $CmdLine[0]2 then $keys[2]=$CmdLine[3]
    if $CmdLine[0]>3 then $keys[3]=$CmdLine[4]
    if $CmdLine[0]>4 then $keys[4]=$CmdLine[5]
    if $CmdLine[0]>5 then $keys[5]=$CmdLine[6]
    ;if $CmdLine[0]>6 then

    if StringInStr($keys[1], “!”) then Opt(”SendKeyDelay”, 200)
    if StringInStr($keys[1], “+”) then Opt(”SendKeyDelay”, 200)
    if StringInStr($keys[1], “^”) then Opt(”SendKeyDelay”, 200)
    if StringInStr($keys[1], “#”) then Opt(”SendKeyDelay”, 200)

    ; AutoLog(”wait for ” & $watch)
    ; AutoLog(”Send ” & $keys[1])

    ;Wait a maximum of 5 seconds for “titled” to exist and be active
    WinWaitActive($watch, “”, 10)
    If WinActive($watch) Then
    sleep(2000)
    send($keys[1])
    if $keys[2]>”" then
    sleep(10000)
    send($keys[2])
    EndIf
    if $keys[3]>”" then
    sleep(10000)
    send($keys[3])
    EndIf
    if $keys[4]>”" then
    sleep(10000)
    send($keys[4])
    EndIf
    if $keys[5]>”" then
    sleep(10000)
    send($keys[5])
    EndIf
    EndIf
    Exit

    ; ===================================================================
    Func AutoLog($sometext)
    if $FileLogging Then
    $LogFile = FileOpen($LOGNAME,1)
    if ($LogFile -1) then
    FileWriteLine($LogFile,$sometext)
    FileClose($LogFile)
    EndIf
    EndIf
    EndFunc ;==>AutoLog
    ; ===================================================================

  36. Greg Says:

    I’d love a script that could show the current keystrokes and mouse clicks in an opaque window. I’m doing some screencasting and recording and would like my recording to show when I type something or when I use a mouse button

    ie: An opaque window that temporarily pops up with “Shift-RightClick” after the key sequence.

    Greg

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>