Showing posts with label AutoIt. Show all posts
Showing posts with label AutoIt. Show all posts

27 May 2018

RoboBackup2 - a script to backup to multiple destinations

In a previous article titled Windows PC Backup Strategy I explored the different types of backups. One of the areas I emphasised was that of backing up your data files (File Backup) on a regular basis and to different locations. I discussed how ideally it would be best to have a backup solution that was not propriety, that the files it would create could be read easily and would always be accessible, even in the future.

Previously I've written the following backup scripts:
RoboBackup - a simple script using RoboCopy, it had folder recycling.
RoboBackup7z - similar but it used a combination of RoboCopy and 7-zip to backup files.

In this article we'll take it a step further, combining backup recycling and archiving features. Also, adding the ability to backup from multiple sources to multiple destinations. This new script is called RoboBackup2:


Source
Here's the source code for the script:

#cs ----------------------------------------------------------------------------

RoboBackup version 2

 AutoIt Version: 3.3.10.2
 Author:         Michael Gerrard, http://mgxp.blogspot.com

 Script Function:
 Create multiple backups of the same data using the RoboCopy mirror function

#ce ----------------------------------------------------------------------------

; Set variables
$title    = "RoboBackup"
$ini   = @ScriptDir & "\RoboBackup.ini"
$retry    = IniRead($ini, "settings", "retry", "1") ;number of retries
$wait   = IniRead($ini, "settings", "wait", "2") ;sec to wait
$exclude  = IniRead($ini, "settings", "exclude", " ") ;files to exclude
$attrib   = IniRead($ini, "settings", "attrib", "/A-:SH /A+:R") ;attributes
$parameters  = IniRead($ini, "settings", "parameters", " ") ;more parameters
$backups   = IniRead($ini, "settings", "backups", "3") ;number of backups
$count   = IniRead($ini, "settings", "count", "1") ;count of backups
$destPath  = IniRead($ini, "destination", $count, @ScriptDir)
$dest   = $destPath & "\Backup" & $count ;Backup1, Backup2, etc
$log   = @ScriptDir & "\Backup" & $count & "_Log.txt"
$7za   = @ScriptDir & "\7za.exe"  ;the 7-zip command line exe
$archPass  = IniRead($ini, "archive", "password", Random(10000000, 99999999, 1))
$archPassPath         = IniRead($ini, "archive", "list-path", @ScriptDir)
$archPassFile         = $archPassPath & "\ArchiveList.ini"
$archSize  = IniRead($ini, "archive", "volume-size", "300m") ;300MB default
$archPath  = IniRead($ini, "archive", "path", @ScriptDir) ;archive path
$archLast  = IniRead($ini, "archive", "last", "0000-00") ;last archive?
$archNow  = @YEAR & "-" & @MON  ;year and month now, used as the file name
$arch   = $archPath & "\Archive\" & $archNow  ;path and filename
$archZip  = IniRead($ini, "archive", "zip", "no")
If $archZip = "yes" Then
 $zip = "-tzip" ;set to zip
Else
 $zip = "-t7z" ;if not set, use the native 7z format
EndIf

; Read the Source folders into an array
$aSource   = IniReadSection($ini, "source")
If @error > 0 Then ;if there are no source folders, add default ones
 IniWrite($ini, "source", "1", @UserProfileDir & "\Documents")
 IniWrite($ini, "source", "2", @UserProfileDir & "\Pictures")
 IniWrite($ini, "source", "3", @UserProfileDir & "\Music")
 IniWrite($ini, "source", "4", @UserProfileDir & "\Videos")
 IniWrite($ini, "source", "5", @DesktopDir)
 IniWrite($ini, "source", "6", @FavoritesDir)
 MsgBox(16, $title, _
 "ERROR: No source folders have been specified in the INI." & @CR & @CR & _
 "The default source folders have been added to the INI." & @CR & @CR & _
 "Click OK to exit the backup:" & @CR & _
 " - The ini will open automatically" & @CR & _
 " - Review/edit the source folders" & @CR & _
 " - Run the backup again")
 Run("Notepad " & $ini)
 Exit
EndIf

; Check if home folder has a space in it
If StringInStr(@ScriptDir, " ") > 0 Then
 MsgBox(16, $title, "ERROR: " & $title & " cannot run!" & @CR & @CR & _
 "The home folder must *not* contain spaces." & @CR & @ScriptDir)
 Exit
EndIf

; Check if the destination path is ok
If DirCreate($destPath & "\T_E_S_T") = 0 Then
 $destOK = MsgBox(21, $title, "ERROR: " & $destPath & " NOT FOUND!" & @CR & @CR & _
 "If the destination is a USB drive please make sure it is plugged in" & @CR & _
 "and click Retry. This window will timeout in 2 minutes.", 120)

 ; Retry
 If $destOK = 4 Then
  If DirCreate($destPath & "\T_E_S_T") = 0 Then
   MsgBox(16, $title, "ERROR: " & $destPath & " still NOT FOUND!")
   Exit
  EndIf
 Else ;if Cancel...
  Exit
 EndIf
EndIf
; If successful remove the test folder and continue
DirRemove($destPath & "\T_E_S_T")

; Backup using the Destination paths
If FileExists($log) Then FileDelete($log) ;delete the existing log
For $s = 1 to $aSource[0][0] ;read each source folder one by one
 $source = '"' & $aSource[$s][1] & '"'  ;format the source folder

 ; Run RoboCopy
 $roboError = RunWait("ROBOCOPY " & $source & " " & $dest & "\" & $s & _
 " /MIR /R:" & $retry & " /W:" & $wait & " /LOG+:" & $log & " /TEE" & _
 " /XF desktop.ini thumbs.db *.tmp " & $exclude & " " & _
 $attrib & " " & $parameters, @ScriptDir, @SW_MINIMIZE)
Next

; If RoboCopy returned a serious error, give a warning
If $roboError > 7 Then
 MsgBox(16, $title, "ERROR: Please review the log file for Backup" & $count)
 Run("notepad " & $log) ;Display the log file
Else
 ; Test that the archive folder can be written to
 $testOK = DirCreate($archPath & "\T_E_S_T")
 DirRemove($archPath & "\T_E_S_T")

 ; If the back was successful then check if it's time to Archive
 If $archLast <> $archNow AND FileExists($7za) AND $testOK = 1 Then
  DirCreate($archPath) ;make sure the archive folder exists

  ; Create an archive file for each source folder
  For $s = 1 to $aSource[0][0]
   RunWait($7za & " a -r " & $zip & " -v" & $archSize & " -w -y -p" _
   & $archPass & " " & $arch & "(" & $s & ") " & _
   $dest & "\" & $s & "\*.*", @ScriptDir, @SW_MINIMIZE)
  Next

  ; Update the ini file and display the backup and archive message
  IniWrite($ini, "archive", "last", $archNow)
  IniWrite($archPassFile, "archives", $archNow, $archPass)
  MsgBox(64, $title, "Backup" & $count & " OK" & @CR & _
  "Archive created: " & $archNow)
 Else  ;no error and no archive
  MsgBox(64, $title, "Backup" & $count & " OK")
 EndIf
EndIf

If $count >= $backups Then $count = 0 ;reset the counter
IniWrite($ini, "settings", "count", $count + 1) ;update the count ini
Exit

Copy and paste the above script into a text editor (Notepad for example). Save as RoboBackup.au3

Compile the RoboBackup.exe - to do this you will need AutoIt installed. You can download AutoIt from here: https://www.autoitscript.com

For the archive to work you'll also need the 7za.exe. You can download it free of charge, full details can be found here: https://mgxp.blogspot.com/2016/04/7-zip-7za-command-line-zip-tool.html 


Quick Start Tutorial
RoboBackup2 can run from almost anywhere, directly from a USB drive or from your local hard disk drive. The only restriction is that it cannot be on the Desktop or in another location where there are spaces in the folder path.

RoboBackup2 can be used in different ways depending on your requirements, the different scenarios. Later we'll look at some complex scenarios but just to begin, for your understanding of what RoboBackup2 can actually do, let's start with a simple scenario: Backup all documents, pictures, music, etc, from C: to D:

In our example we've created a folder D:\RoboBackup2, this will be our 'home folder' and we have put our compiled script, RoboBackup.exe in that folder. Double click RoboBackup.exe and (by default) the following folders (files and sub-folders included)...
C:\Users\<username>\Documents
C:\Users\<username>\Pictures
C:\Users\<username>\Music
C:\Users\<username>\Videos
C:\Users\<username>\Desktop
C:\Users\<username>\Favorites
...will be copied to D:\RoboBackup2\Backup1, etc...

While RoboBackup2 is running an icon appears in the task bar:
You can open that and see what's happening if you wish. If you close it, RoboBackup2 will be closed and the backup will be cancelled (and incomplete). Just keep in minimised, you can continue working while it is running.

Once it has finished, RoboBackup2 will display a message saying "Backup1" has finished. Now you'll have a new folder D:\RoboBackup2\Backup1. This is where the backed up files are stored. There are sub-folders below that are numbered 1-6. They represent the six default source folders that are backed up. 1=Documents, 2=Pictures, etc (see above list). Also, in the D:\RoboBackup2 folder you'll find a log file Backup1_Log.txt - this is a log file that explains in detail which files were copied, if there were errors and more.

Run RoboBackup.exe again, a second folder will be created called Backup2.
Run RoboBackup.exe a third time and Backup3 will be created.
Run RoboBackup.exe a forth time and Backup1 will be updated. Only those files that have been changed on C: will be copied. Any files that were deleted in the source folder will be deleted from the Backup1 folder.

The above behaviour is called recycling, this is explained in more detail later in this article.

If 7za.exe is present in the 'home' folder (D:\RoboBackup2 in our example) a password protected archive will be created once a month - more details below.

Many of the defaults can be changed using the RoboBackup.ini file. The following explains how you may configure RoboBackup2 to meet your needs.


RoboBackup.ini
How RoboBackup behaves can be configured using the RoboBackup.ini file. It is automatically created the first time you run the script or you can create it yourself from the beginning. Here is a copy of the ini with the default settings:

[source]
1=C:\Users\<username>\Documents
2=C:\Users\<username>\Pictures
3=C:\Users\<username>\Music
4=C:\Users\<username>\Videos
5=C:\Users\<username>\Desktop
6=C:\Users\<username>\Favorites

[settings]
count=1
backups=3
retry=1
wait=2
exclude=
attrib=/A-:SH /A+:R
parameters=

[archive]
path=
list-path=
volume-size=300m
last=
password=
zip=

[destination]

In the Source section you may continue adding as many folders as you wish. All folders and their respective sub-folders will be included in the backup. When backed up the folders appear as their respective numbers. For the above example you would have:
Backup1\1
Backup1\2


Settings
In the RoboBackup.ini there is a section titled settings. Let's explain them one-by-one:

count=1
This increments every time you run the script. It is how the script keeps track of which backup to make. Normally leave this alone.

backups=3
The number of backups. The default is 3 meaning that folders backup1, backup2 and backup3 will be created after running the script three times. If you set this to 4 then four backups will be made, if you set it to 5, five will be made, etc.

retry=1
This is the number of times Robocopy will try to copy the file. For example, if a file is locked for editing then Robocopy will not be able to copy it. With retry=1 it will try one more time. After that it will give up and the log will show this file was not backed up. Normally retry=1 is fine but if you are backing up files from a network shared drive you might consider changing this to retry=3 or more. However, the more retries, the slower the backup as it takes time to try again - see the next wait=.

wait=2
This is related to retry=x. The number of seconds to wait before retrying. For example, if you use retry=2 and wait=30 then it will take an extra minute until moving to the next file. This functionality is directly from the Robocopy command, please have a look on the web for more information.

exclude=
By default (exclude=) the following files are not included in the backup:
desktop.ini
thumbs.db
*.tmp

To add to this list and exclude more files use the exclude= parameter. You can specify multiple files by putting a space between each. For example:
exclude=*.mov *.mp4
The above would exclude all files ending in mov and mp4. This is in addition to the hard-coded desktop.ini, thumbs.db and tmp files.

attrib=/A-:SH /A+:R
By default files backuped up have the System and Hidden attributes removed (it's good to see the files you have backed up). The backup up files in the destination are set to Read-only. The idea is to stop backed up files being accidentally deleted or changed. However, in practice it is very easy to delete or change a read-only file so this is not very serious protection. The default configuation is included by default for you to modify as you wish. If you remove it and leave attrib= then no attribute changes would be made.

parameters=
Robocopy has lots of parameters and if you'd like to add something specific you may, using parameters=. For example, perhaps you want to restrict files of a certain size being included in the backup? You could do this by adding:
parameters=/MAX:1073741824
The number is bytes, the above would stop incidvidual files of 1GB and over from being included in the backup.

If you are interested in knowning more about the functionality and further parameters you could use, look up Robocopy on the web or look at its help from the command line (robocopy /?).


Backup Recycling
Every time you run the backup, if a new folder was created you would soon run out of storage space. This is especially true if you backup every day. Also, it would take a long time to backup all the files each time. It would make more sense if you would replace your oldest backup at some point. If only the changed files were replaced, this would speed up the backup time considerably. Therefore the script works like this:


It creates one backup each time it runs. By default three backups are created, when the script runs for a fourth time, the first backup is recycled. Here's an example:
  • The first time the script is run Backup1 is created.
  • The second time and Backup2 is created.
  • The third time and Backup3 is created.
  • The forth time and Backup1 is updated.
  • The fifth time and Backup2 is updated.
  • The sixth time and Backup3 is updated.
  • The seventh time and Backup1 is updated.
  • It continues like this...
Where it updates, that is actually a file/folder synchronisation. It is very fast because only those files that have changed are updated.

The number of backups can be changed from 3 to any number you wish. In the ini file, under [settings] add the line backups=X where X is the number of backups you would like. For example, set it to 7 and run the script every day to have a daily backup (assuming the script is run only once a day).


Destination
Each backup folder is created in the script folder by default. However, you can decide where each backup folder is stored. In the ini there is a [destination] section. Add the destination folders you need. This means you could spread your backups over a number of different locations/drives.

For example, you might have:
[destination]
2=D:
3=K:

This would mean that backup 1 would be stored in the home folder (where the RoboBackup2 script is). Backup 2 would be saved to D: and backup 3 to drive K:. Dispersing the backups like this means if one backup drive fails, another will be fine. You could also put one or more of these backup drives in a safe place, perhaps off-site.


Archive
This is an optional feature. If the 7za.exe file is present in the home folder, once a month the backup runs as usual but after the backup is complete it is compressed into archive 7z file(s). An archive is created for each source folder in the backup. For example:
Backup1\1
Backup1\2

The above would archive as (assuming the date was October 2017):
2017-10(1).7z
2017-10(2).7z

In the above example two archive files are created, one for each source folder backed up. Also, each archive file is split into volumes. By default 300MB volumes. This means that if a total backup was 700MB, one folder was 500MB and contained 200MB, you would have the following archive files:
2017-10(1).7z.001
2017-10(1).7z.002
2017-10(2).7z.001


The archive files are encrypted (AES-256) with a password. The password is an eight digit random number. Every time the archive runs the ArchiveList.ini file is updated with the name (year-month) of the archive and the password. The ArchiveList.ini is created in the home folder by default but you can also specify where it is stored using the list-path= parameter. This is important because it is best to keep the passwords separate from where you store the archive. But don't lose the ArchiveList.ini file - cracking AES-256 encryption is close to impossible! Archive files are always encrypted.

If you don't need such security, you can specify a generic password with the password= parameter. For exmaple you could put password=12345

By default the native 7-zip format (.7z) is used for the archive files. If you would like to use the zip format, add the following to the [archive] section of the ini:
zip=yes
(it is case sensitive)

If you do not wish to use the archive feature you can disable it altogether. To do this simply delete the 7za.exe file. If the script does not see the 7za.exe it will not attempt to create an archive.

By default the archive file is created in a folder called "Archive" where the script is (and Backup folders). It is possible to specify a separate destination path for the archive. Here's an example:
[archive]
path=K:

After it runs for the first time you'll have a K:\Archive folder and all archive files (7z or Zip) will be stored here.

The first time the script runs it will check to see if this path exists. If it does not, the archive will not be created, the archive process will be skipped. No error message appears. The next time the script is run, again it will look for this path, if not found, it will skip the process.

The idea is that the archive backup drive (USB removable hard disk, flash drive, etc) will not be connected to the computer all the time. Therefore, when it is plugged in, possibly just once a month, when the script runs the archive will be made. This is why no error message appears when the path is not found. It is assumed that is your choice, that you will plug the archive drive in later.


Error
Once RoboBackup has finished it will display a message stating that the backup completed. If there is an error, perhaps there is not enough space on the destination drive, the following message will appear:


If you see a message like this, review the corresponding log file, it will explain what happened.


Example Backup Scenario 1
In the tutorial at the beginning of this article we described a simple backup solution where files from C: would be copied to backup folders on D:. This was assuming D: was a local drive. However, it would be safer if it were a removable drive, you would be able to put it in a safe place after the backup had finished.


Put the RoboBackup2 home folder on drive G: (the USB flash drive in the above example). Run RoboBackup.exe and it will backup from the C: to G:, creating backup folders such as:
G:\RoboBackup2\Backup1
G:\RoboBackup2\Backup2
G:\RoboBackup2\Backup3

That is a nice simple backup. Of course it does mean that if that USB flash drive dies, you've lost all your backups.


Example Backup Scenario 2
This is very similar to the first scenario but we have two USB flash drives:


Again store the RoboBackup2 home folder on drive G:. In the Destination section of the RoboBackup.ini add the following:
[destination]
3=H:

After you've run RoboBackup at least three times you will have the following backups:
G:\RoboBackup2\Backup1
G:\RoboBackup2\Backup2
H:\RoboBackup2\Backup3

This would mean that every third backup would be stored on the second USB drive. This could be useful for two reasons; 1) if one USB drive dies you still have the other, 2) if three backups would not fit on one USB drive.

Of course you could set this up in any way you wish.You could store the RoboBackup2 home folder on the D: drive and specify the Destinations for backups 2 and 3 to be on the USB drives. You'd have three backups on three separate devices. Or use three USB drives... or...

IMPORTANT: If the USB drive is not present when the backup runs, the backup will fail. Look in the log file for an explanation.


Example Backup Scenario 3
In this scenario we'll see the real power of RoboBackup2:


The two USB drives would be plugged in all the time.

The RoboBackup2 home folder would be stored on G: (the first USB drive).

In the Settings section of the ini file the number of backups would be limited to two:
[settings]
backups=2

In the Destination section H: would be specified for the second backup:
[destination]
2=H:

The above would spread the backups over the two USB drives, this would mean you'd have two backup copies available at all times. If one USB drive died, the other would be available, so you'd have at least a backup from yesterday or the previous day at the worst.

In addition in the ini the Archive section should look like this:
[archive]
path=M:

The drive you use for the archive should have plenty of disk space, this is why in the diagram it's shown as an external USB hard disk drive. One archive would be created once a month, the first time during the month that the drive was plugged in. This means that if you forget to plug drive M: in, it doesn't matter. Just plug it in the next time RoboBackup2 is run and it'll create the archive.

An advantage of using the archive feature is that you should unplug that drive and store it somewhere else, even off-site. Only plug it in once a month. This is a good idea because if a virus hits your computer it might infect any connected drives. Having at least something disconnected is always a good idea and this could be a good system for you. It still requires some discipline from your side of course!

Don't forget that when the archive runs the ArchiveList.ini is created in the home folder. Keep that file safe as all archive files are password protected, the random password is stored in the ArchiveList.ini file.


Conclusion
I've been using this script for real for well over a year. It works well. It's meant some peace of mind. I know my backups are there and accessible. I know that every month there's an additional copy (the archive) that I can always refer to. Indeed having that monthly archive is great in case a month or so down the line I realise I should not have deleted a file. I can still get it back.

This script isn't for everyone of course. But there is something nice about having a script rather than a backup program with a user interface. With a script like this you set it up once and just let it do its thing. Don't forget you could schedule the RoboBackup.exe to run at a certain time every day using the Windows Task Scheduler.

I hope you've found this script interesting. Feel free to use it how you wish, of course a little credit would be nice. Maybe you found a better way to code something? Maybe you expanded the functionality? Please reply in the comments below!


Disclaimer
My script works fine for me but I accept no liability for anything here. I'm providing this script source code and this article for you to work with as you wish. Use at your own risk! If you lost data from a backup not working, again this is nothing to do with me, all of what I've explained here is just my opinion, my advice.


16 Feb 2018

List the members of an Active Directory group

From a Windows computer would you like to see a list of the members of a particular Active Directory (network) group? In this article we'll explore how to do this and how to extract and rearrange the usernames into a conventional vertical list.

List the members of a group
Open a command window - press Win-R, type CMD and press Enter
Enter the command: NET GROUP "your group name" /domain

You should replace "your group name" with the name of the group you wish to see the membership of. Remember that the double quotes " " are important, often Active Directory group names have spaces in them, using the quotes is essential for the group name to be recognised. 

Here's an example:


The result is OK. The users in the group are listed under the dotted line. The only thing that's not good is that they are listed in three columns. This makes it difficult to easily extract these usernames for other uses. For example, you may wish to send an e-mail to everyone in this group or display this list in a report. This problem is especially acute when there are many hundreds of group members.


Create a vertical list of usernames
The aim is to create a list as follows:
RIPLEY
DALLAS
ASH
LAMBERT
KANE
PARKER
BRETT
This is much easier to work with in Excel or Outlook.

I've written a small script using AutoIt. Before you go further, ensure you have AutoIt installed on your computer. It's an excellent scripting language because after you create your script you can compile it to an EXE and use it standalone, without having to install anything on the computer where you use it. More information on AutoIt can be found here:
https://mgxp.blogspot.ch/2013/05/autoit-scripting-language-for-windows.html

The script I've written is called Membership. It runs the above NET GROUP command, the output is written to a text file. That file is read by the script, the names are extracted and written to a new text file in order vertically. 


Source Code

#cs ----------------------------------------------------------------------------
 Membership.au3
 AutoIt Version: 3.3.14.2
 Author:        Michael Gerrard, mgxp.blogspot.ch, February 2018

 Script Function:
 List users who are the members of an AD group to a file.

#ce ----------------------------------------------------------------------------

$group      = "your group name"  ;change to a valid AD group name!
$title      = "Membership"
$inputFile  = @ScriptDir & "\membership.tmp"
$outputFile = @ScriptDir & "\membership.txt"
$n          = 8 ;line counter (starts at 8)
$u          = 1 ;user counter

; Run the NET GROUP command to list the users
RunWait(@ComSpec & ' /c NET GROUP "' & $group & '" /domain > ' & $inputFile, @ScriptDir, @SW_MINIMIZE)

; Open the input file and read the lines
$file  = FileOpen($inputFile, 0) ;open read only
$aFile  = FileReadToArray($file)
If @error Then  ;An error occurred reading the current script file
    MsgBox(16, $title, "There was an error reading the file.")
 Exit
EndIf
FileClose($file)

; Step through the lines and output the usernames to the output file
$file = FileOpen($outputFile, 2) ;create a new file
While $aFile[$n] <> "The command completed successfully." ;loop through the lines

 $aSplit = StringSplit($aFile[$n], " ") ;split the line into users
 For $u = 1 To $aSplit[0] ;step through the possible users

  $ws = StringIsSpace($aSplit[$u]) ;some users are white spaces
  If $ws = 0 Then ;if not white space
   FileWriteLine($file, $aSplit[$u]) ;write the user to the output file
  EndIf
 Next ;loop again to find another user

 $u = 1  ;reset to 1
 $n = $n + 1 ;increment the loop
Wend

FileClose($file)
FileDelete($inputFile) ;delete the temporary input file
Run("notepad " & $outputFile, @ScriptDir)
Exit

Copy and paste the above code into a text file.

Save the text file as Membership.au3

The first line in the code is where a variable is defined for the group name:
$group = "your group name"
Change the text in double quotes to the name of the your group.


Run the script
As long as you have AutoIt installed you can either run the Membership.au3 file or compile it to an EXE for standalone use.

Remember to change the variable $group to the group name of your choice before running or compiling the script.

NOTE: For the script to work it should be in a folder with a path structure without spaces. For example, if it's in D:\VeryImportant\Files that will work fine. If it's in D:\Very Important\Files then it will not work.

When you run the script it will open Notepad with the usernames in a vertical list like this:


From Notepad you can copy/paste the list to Excel, Word or where ever. Also, it is possible from Excel PowerView to query this text file, this can be useful if you wish to match it to other data you may have in a corporate database.


Conclusion
It's a real shame that the NET GROUP command doesn't have the ability to list the names vertically to start with. However, using AutoIt it's possible to get around this and make a simple but effective solution. I hope this is of help to you.






25 Jan 2018

Close Java AutoIt Script

If you are running a program that relies upon Java Runtime, sometimes it crashes and even using End Task doesn't seem to remove everything from memory. I was often having this problem so I wrote a small script with AutoIt to look for Java and close it, over and over again until it is gone from memory! You could adapt this script to close any troublesome program of course, just change the $proc= variable line in the script below.

Here's the script in case you find it useful:

#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.10.2
 Author:         Michael Gerrard, http://mgxp.blogspot.com

 Script Function:
 Close a process

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

$title  = "Close Java"
$proc  = "jp2launcher.exe"

If ProcessExists($proc) > 0 Then ;if it is running...

 ; Confirm that it should be closed
 $ok = MsgBox(33, $title, "Close " & $proc & "?")
 If $ok = 1 Then ;if OK
  While ProcessExists($proc) > 0
   ProcessClose($proc)
   Sleep(500) ;pause half a second
  Wend
 Else ;if Cancel
  Exit
 EndIf

 ; Check again to see if it is running now...
 If ProcessExists($proc) > 0 Then  ;it is still running
  MsgBox(0, $title, "Failed!")
 Else ;it is not running
  MsgBox(0, $title, "Success!")
 EndIf

Else ;if it is not running...
 MsgBox(0, $title, $proc & " is not running")
EndIf
Exit

Copy the above code, save it in a text file called CloseJava.au3

Compile using AutoIt https://autoitscript.com

Double click the resulting CloseJava.exe, it'll say:


Click OK





Conclusion
Just a small script that demonstrates how useful AutoIt is. Of course I've shown how to close Java but you could use the same script to close a different program. Just alter the $proc= variable.



6 Jun 2016

RoboBackup7z - an AutoIt script to backup files using Robocopy and 7za


Previously I wrote an AutoIt script called RoboBackup. That script used Robocopy to automate backing up files into three (or more) folders. It cycled through those folders synchronising files each time.

In this article I am going to explain a slightly more advanced script that also backs up files but does so by using both the Robocopy command and also the 7-Zip 7za.exe command line program. I've called this backup script 'RoboBackup7z'.

The idea behind RoboBackup7z is that the latest backup is a synchronised folder managed by Robocopy. But previous Robocopy backups are archived in 7z files for safe-keeping. This means the latest data is easy to recover and the previous backups are still available but are smaller compressed files you could copy elsewhere - to DVD or cloud storage perhaps.

First let's have a look at how this script works and after how it is put together. I hope you'll find this interesting.


Setup
The idea is that you create a folder on a removable drive or USB flash drive and run the script from there. In the following screen shot you can see my example:


In the above example I have an external USB hard disk drive that is drive G: on my computer. I am backing up files from my D: drive (source) and so I've created a folder called "D" (I could've called it anything but this makes sense to me).

Inside the "D" folder I have the following files:

  • 7za.exe
  • RoboBackup7z.au3
  • RoboBackup7z.exe
  • RoboBackup7z.ini


Edit RoboBackup7z.ini


Add a folder to backup. This can also be a drive letter, in our example we'll use D:. This backs up all folders and files found on drive D:.


Run
Double click RoboBackup7z.exe

The first time it runs the following will be created:

  • A folder called Backup where a copy of the folders and files will be made.
  • A log file named yyyymmdd_hhmmss_LOG.txt (the RoboCopy log showing what was backed up).

The second time it runs the following happens:

  • A folder called Archive is created
  • 7-Zip runs, it adds all the folders/files from the Backup folder to a 7z archive file in the Archive folder.
  • It names the 7z with the name of the last backup log file (it gets this from the ini).
  • It splits the 7z file into 300MB separate files.
  • The log file is moved to the Archive folder.
  • RoboCopy runs again, the Backup folder is updated with new files, a new log file appears in the script folder.

The third time it runs:

  • The same as the second time, a new 7z is created and stored in the Archive folder with the log file. RoboCopy runs again to update the Backup folder and create a new log file.


In the above example I have run the script more than twice. The Backup folder contains the files of the latest copy and the Archive folder contains the 7z files. The log is the latest log file.

Here's what it looks like inside the Archive folder:


In the above screen shot you can see the txt files are the logs. You can open these in Notepad. They are the original log files produced by Robocopy when it originally ran.

The other files are the 7z files. They are in 300 MB chunks. To view and extract files open the first one (001) with 7-Zip for Windows.

IMPORTANT: There is no control over how much disk space is used or how many backups can be made. You must manage the disk space yourself. Move files from the Archive folder to another location as needed.


Source Code
In the following screen shot you'll see the code as I see it when I writing it. On the left hand side you can see the line numbers. Below the image I'll explain line by line what the script does but first a few basics, here's how the colour coding works:

Green - comments, text to explain what the script is doing. Therefore lines 1 to 11 is just for information.
Black - variables, they also start with a dollar sign $
Blue - functions like IF.
Orange - operators like <>=
Red - text



--- Line 15
This defines the $ini variable that identifies the RoboBackup7z.ini file. It's a configuration file containing the drive/folder to backup and the name of the last log file.

--- Line 17 to 25
These are the variables and what their initial values are. This includes reading data from the ini file.

--- Line 27 to 39
First this checks if the 7za.exe exists. If it does not, it'll skip this part.
If 7za.exe does exist then it'll check for the destination folder (Backup), if this exists then it'll run the 7za program to archive the files from the destination (Backup) folder.

--- Line 32
This is the 7za line. It compresses the files from the Backup folder into one or more 7z compressed (zipped) files. The 7za.exe has a number of parameters:

-r = recurse, meaning to archive sub-folders/files

-v300m = this splits the 7z archive file into smaller files (volumes). In this case we're splitting to 300MB files. You can change this to any size that fits your needs. If you do not use this parameter then the archive will be one large 7z file. Such a file might be very big, depending on what files you have to backup, larger than 2GB, therefore it makes sense to split to smaller files to make them easier to copy. Many services do not support files larger than 2GB.

--- Line 36 and 37
These copy the log file to the Archive folder. This is so the log is stored along with the backup it was made from.

--- Line 42
Save the date (name of the log file) to the ini file. This so it can be used the next time the backup runs to identify the 'last' backup.

--- Line 45
Runs ROBOCOPY to synchronise files from the source to the backup (destination) folder.

--- Line 57
Open Notepad and display the log file. This will happen at the end and shows you what has happened during this backup. It's the usual output from Robocopy.

--- Line 59
Exit just closes the script. You don't really need this but usually put it just to show where it ends.


My RoboBackup7z Script Source Code for Copy/Paste
Here's the same script as shown above in the screen shot. But this time it's text so you can copy/paste it and use it. Feel free you change it :-)

#cs ----------------------------------------------------------------------------

RoboBackup using 7-Zip

 AutoIt Version: 3.3.10.2
 Author:         Michael Gerrard / http://mgxp.blogspot.com

 Script Function:
 Create a backup using Robocopy and archives using 7-zip

#ce ----------------------------------------------------------------------------


; Set variables
$ini   = @ScriptDir & "\RoboBackup7z.ini"

$FolderToBackup = IniRead($ini, "Settings", "FolderToBackup", @MyDocumentsDir)
$source     = '"' & $FolderToBackup & '"'
$dest   = @ScriptDir & "\Backup"
$archive  = @ScriptDir & "\Archive"
$today   = @YEAR & @MON & @MDAY & "_" & @HOUR & @MIN & @SEC
$log      = @ScriptDir & "\" & $today & "_LOG.txt"
$7za   = @ScriptDir & "\7za.exe"
$last   = IniRead($ini, "Settings", "LastBackup", "00000000_000000")
$7zBackup  = $archive & "\" & $last

; Check if a backup was done before, if so, archive it to a 7z file
If FileExists($7za) Then
 If FileExists($dest) Then
  DirCreate($archive) ;make sure the archive folder exists

  RunWait(@ComSpec & " /c " & $7za & " a -r -v300m -w -y " & $7zBackup & " " & _
  $dest & "\*.*", @ScriptDir, @SW_MINIMIZE) ; add to 7z archive file

  ; Move the log to the archive folder
  FileCopy(@ScriptDir & "\" & $last & "_LOG.txt", $archive)
  FileDelete(@ScriptDir & "\" & $last & "_LOG.txt")
 EndIf
EndIf

; Write today's date and time to the ini
IniWrite($ini, "Settings", "LastBackup", $today)

; Run RoboCopy
RunWait(@ComSpec & " /c ROBOCOPY " & $source & " " & $dest & _
" /MIR /R:2 /LOG:" & $log & " /TEE" & " /XF desktop.ini ", @ScriptDir, @SW_MINIMIZE)

; /MIR = mirror
; /R:2 = retry twice
; /LOG: = record to a log file
; /TEE = output to the screen too
; /XF desktop.ini = don't copy the desktop.ini file (avoids getting the My Documents folder name)

; Display the log file
If FileExists($log) Then
 Run("notepad " & $log)
EndIf
Exit


Other required files
For the script to work you'll need Robocopy, this command is included with Windows as standard. Also you'll need the 7za.exe file, you can download it free of charge from http://www.7-zip.org/
For more detailed information please see the following article:
https://mgxp.blogspot.ch/2016/04/7-zip-7za-command-line-zip-tool.html


Conclusion
It's amazing what you can do with free tools! AutoIt is of course the easiest way to make a script that's compact and simple. Just look at how few lines of code I used. Robocopy and 7za too, excellent. This script works very nicely and I've been using it for several months now. But it has some shortcomings. For instance, I have to manage the disk space myself. Also it only backs up from one location (drive or folder location and sub-folders). But this is fine, it means I have more work to do in the future!


Disclaimer
The script here is just an example. I do not provide it with any guarantee. I'm not advocating this script be used for anything specific, this article is just to demonstrate what can be done. Use at your own risk! 


Reference

AutoIt
https://www.autoitscript.com

Robocopy at Wikipedia
https://en.wikipedia.org/wiki/Robocopy

Various articles about Robocopy
https://mgxp.blogspot.ch/search/label/Robocopy
7za, the 7-zip command line program

If you are looking for some help with creating self-extracting archives, please see my previous articles specifically on this more advanced subject:
PART 1 - http://mgxp.blogspot.com/2010/07/create-self-extracting-archive-exe.html
PART 2 - http://mgxp.blogspot.com/2013/01/create-self-extracting-archive-exe-part.html

5 Aug 2015

Robocopy - backup and file synchronisation PART 2

In my first article about Robocopy (click here) I gave an example of how to use the Robocopy command and how to make a simple command file (batch file) to backup (synchronise) a folder.

In this article we will look at how we can automate the use of Robocopy further. This time we'll use AutoIt to control the parameters used and how our backup runs. What's the advantage of using AutoIt over a command file? You can do lots of clever things with AutoIt that would be painful to do with a mere command file.

AutoIt is a free scripting language for Windows. It is easy to learn and creates standalone EXE files. For more on AutoIt click here.


Example Scenario
I want to do the following:
  • Backup files to a USB external hard drive (storage that can be detached from the computer is best in case computer dies your backup won't die with it).
  • A simple solution where I can double click a file and it will backup, no prompts.
  • I don't want to overwrite my backup each time I run it. Imagine if I make a mistake, run the backup, my mistake would be backed up. I need a solution for this.
  • A log or report of what's been backed up.
  • It should be efficient and fast, only changed files backed up.
Of course your needs maybe different but I hope that at least this article will give you a few ideas as to how you can use Robocopy and AutoIt together to do some amazing things! 


My AutoIt and Robocopy Example Solution
I wrote a script call RoboBackup.au3. I wrote it using AutoIt in the custom SciTE editor available from AutoIt's website.

In the above example scenario I state that I'd like to be able to run the backup multiple times and not overwrite each time. To do this I decided to make my script manage three backups (by default). What this means is that I'll have three folders; backup1, backup2, backup3. Each time the backup script is run it will copy files to each folder consecutively (one by one). Because it's using Robocopy not all the files will be copied each time, only those changed since. However, it won't be since the last backup, but since three backups ago. That's a compromise on my part otherwise the script might've become more complex, I want to keep it as simple as possible. Anyway, the general concept is that you can have a maximum of three backups at any one time. This should cover most situations. 


In the above screen shot you'll see the code as I see it when I writing it. On the left hand side you can see the line numbers. I'll explain line by line what the script does but first a few basics, here's how the colour coding works:

Green - comments, text to explain what the script is doing. Therefore lines 1 to 11 is just for information. 
Black - variables, they also start with a dollar sign $
Blue - functions like IF.
Orange - operators like <>=
Red - text
Yellow - internal 'macros', these start with @ and are like system variables.

--- Line 15
So that the script 'knows' which backup folder (1, 2 or 3) to use there has to be an INI configuration file to hold these settings. Line 15 creates a variable $ini with the name of the file: RoboBackup.ini. The @ScriptDir means the current folder.

--- Line 16
$number is the number of backups folders you want to use. By default there are three. This can be changed though, if you put a different number in the ini file, that number will be read and used instead of 3. 

--- Line 17
$count is used to keep count of which folder was backed up last.

--- Line 19 
Folder to backup - this script will backup one folder but all sub-folders are included. You can specify the folder name in the ini file or it will use the My Documents folder.

--- Line 20
In case the folder to backup has spaces in it, double quotes are added. This is important because the $source variable will be used on the Robocopy command line where any spaces without double quotes " " would cause trouble.

--- Line 21 
The destination is Backup1, Backup2, etc. The number on the end comes from the ini, the $count variable. This means you'll maintain multiple backups.

--- Line 22
The log file is named as RoboBackupLOGx.txt where "x" is the number ($count) of the backup. If you are using the default settings there will only be three log files created. Each time the backup runs the old log file with the same name will be overwritten. I've done it this way so there are not lots of log files created. However, you might prefer to have more comprehensive logging than the simple three log file approach I've used. For example, you could change this line to create a log that has the date in it, meaning that a log file will be created every time the script is run and it will remain until you delete it (it will not be overwritten unless you run the script twice on the same day):

$log = @ScriptDir & "\RoboBackupLOG" & @YEAR & @MON & @MDAY & "_" & $count & ".txt"

The above would create a file name like this: RoboBackupLOG20150803_1.txt
I've put the date backwards, year-month-day, to ensure that all the logs will line up when you look at them in explorer. The last digit is the count, it'll tell you which backup folder to look in.

--- Lines 25 and 26
These lines increment the $count. When the $count is greater than the $number, it resets. This is for naming the backup folders 1, 2, 3 and then going back to 1 and starting again.

--- Lines 29 and 30
This is actually one line. At the end of line 29 you'll see an underscore "_" in AutoIt this means to start a new line. The only purpose here is for readability as it's a long command line so I wanted to split it to two lines. Just imagine it is one long line though. You can see that this is the Robocopy command itself! It's run using the AutoIt function RunWait(). It opens a command window and runs a command. In my script I've done this but minimised the command window. It's nice like that because you can check it if you want. However, if you prefer you can hide it altogether. 

--- Lines 32 to 36
Comments, an explanation of the command line parameters for Robocopy that I used. For line 36, regarding the RoboCopy /XF command, this is to stop RoboCopy coping the desktop.ini file. The Desktop.ini sometimes has a command inside it to show a different folder name. This is the case for My Documents and it can cause confusion. Not including the Desktop.ini means that the folders appear with their real names.

--- Line 39
Open Notepad and display the log file. This will happen at the end and shows you what has happened during this backup. It's the usual output from Robocopy. 

--- Line 40
Exit just closes the script. You don't really need this but usually put it just to show where it ends.



My RoboBackup Script Source Code for Copy/Paste
Here's the same script as shown above in the screen shot. But this time it's text so you can copy/paste it and use it. Feel free you change it :-)

#cs ----------------------------------------------------------------------------

RoboBackup

 AutoIt Version: 3.3.10.2
 Author:         Michael Gerrard

 Script Function:
 Create three backups of the same data using the RoboCopy mirror function

#ce ----------------------------------------------------------------------------


; Set variables
$ini   = @ScriptDir & "\RoboBackup.ini"
$number   = IniRead($ini, "Settings", "Number", "3")  ; number of backups
$count   = IniRead($ini, "Settings", "Count", "1")   ; count of backups (where we are now)

$FolderToBackup = IniRead($ini, "Settings", "FolderToBackup", @MyDocumentsDir)
$source   = '"' & $FolderToBackup & '"'
$dest   = '"' & @ScriptDir & '\backup' & $count & '"'
$log   = @ScriptDir & "\RoboBackupLOG" & $count & ".txt"

; Increment the count
If $count >= $number Then $count = 0
IniWrite($ini, "Settings", "Count", $count + 1)

; Run RoboCopy
RunWait(@ComSpec & " /c ROBOCOPY " & $source & " " & $dest & _
" /MIR /R:0 /LOG:" & $log & " /TEE" & " /XF desktop.ini ", @ScriptDir, @SW_MINIMIZE)

; /MIR = mirror
; /R:0 = retry zero times
; /LOG: = record to a log file
; /TEE = output to the screen too
; /XF desktop.ini = don't copy the desktop.ini file (avoids getting the My Documents folder name)

; Display the log file
Run("notepad " & $log)
Exit

Here's what to do:
  • Select the above text, press Ctrl-C to copy it. Switch to your text editor (SciTE) and press Ctrl-V to paste. 
  • Make sure you have AutoIt installed. 
  • Compile and run the script. 

RoboBackup.ini
The RoboBackup.ini is just a text file. You can create this yourself in Notepad or in any case you'll see it is created by the script the first time you run it. I'll look like this:

[Settings]
count=2
number=3
FolderToBackup=C:\YourData

The count is the variable the script reads and it will change every time you run the script. In my example above it says "2" so the latest backup is number 2. Next it'll be 3 and then 1, etc. This line is generated automatically by the script. 

The number line is optional. I have it set to 3, the default. But you can change this to 4 or 8, whatever. This is the number of backup copies you'd like.

The FolderToBackup line is also optional. By default it'll backup your My Documents folder. If you want to backup something else you can specify the folder here. All sub-folders below it will be included in the backup.


Where to put the files
To use the script put the compiled RoboBackup.exe and the RoboBackup.ini files in the destination drive. For example, if you have a USB flash memory drive or a USB hard disk drive, make a folder called backup on it, copy the files RoboCopy.exe (and RoboBackup.ini) into that folder. Run the script from that folder, it'll create the Backup1, Backup2, etc, folders below that point. This is a nice way of working because it means you can unplug your removable backup drive and put it somewhere safe. The next time you want to backup, plug it in and run RoboBackup.exe. 


IMPORTANT: Disk Space 
The main purpose of this script is to make a number of backup copies. This is so that you don't overwrite your backup each time, that you have a chance to recover files from a previous backup. However, to make this all work you do need to be aware of the disk space required for the backup. I've not included any disk space checks in the script (maybe in version 2!!! ;-)). Therefore look at what you want to backup and make sure your backup drive has enough space to accommodate multiple copies of that data. Also factor in that the data will grow in size as you use it. 


Conclusion
RoboCopy is a powerful command line tool for file/folder synchronisation on its own. Combined with AutoIt you can make a script that provides much more control. Here I've provided just one example and I hope it's given you ideas for how it can be adapted to solve your backup requirements. Often the simplest form of backup is best. Imagine with this, restoring is easy, just copy the files. Also for the backup itself it's easy with few requirements, just one standalone exe file (your script, RoboCopy is included as part of Windows by default) and enough disk space. This is a free solution too!


Disclaimer
The script here is just an example. I do not provide it with any guarantee. I'm not advocating this script be used for anything specific, this article is just to demonstrate what can be done. Use at your own risk! 


Reference

AutoIt 

My first RoboCopy article explaining the Robocopy command itself:


9 Jun 2013

AutoIt - Create Year and Month folders

Year and Month foldersIntroduction
I wanted to create folders from 1998 to 2013. With sub-folders for all the months 01 to 12 in each.

1998
Sub-folders 01 to 12 to represent the months.

1999
Sub-folders 01 to 12 to represent the months.

2000, etc... The image opposite shows what it should look like.

I did not want to create these folders manually in Windows Explorer, it would've taken too long and it's a boring job. Perhaps I'd need to do this again another time, having a script (a program) I could run to do this quickly seemed to be a good idea.

There are a few ways of doing this in an automated way. You could create the series of folders in Excel as a column. Then in column A you could put MD (Make Directory). Then copy/paste that to a text file and you could make a batch file to create the folders for you. Of course this method is not elegant and you can't easily reuse it.

A good alternative is to use AutoIt. You can quickly make a script and modify it later if need be. Here in this article I'll show you how to do this. We will use For...To...Next loops.


AutoIt
It's a scripting language for Windows, it is free and you can download it from here: www.autoitscript.com
Also, there's my previous article introducing AutoIt here.


Code
Here's my code, feel free to copy/paste it.

#cs ----------------------------------------------------------------------------
CreateYYYYMM
Create a folder structure of YYYY\MM (year and month)
By Michael Gerrard, 9/6/2013
#ce ----------------------------------------------------------------------------

; Script Start 

$title   = "Create Year and Month folder structure" 
$home    = @ScriptDir
$startY  = "1998"
$endY    = "2013"
$startM  = "1"
$endM    = "12"

; Loop and create the Year folders
For $y = $startY to $endY Step 1
    
    ; Create Year folder
    DirCreate($home & "\" & $y)
    
    ; For each year folder create a sub-folder for Months
    For $m = $startM to $endM Step 1
        
        ; You need folders that are MM so you need to check if it's just one character
        ; then add a 0 to the front to make months like 01, 02, 03, etc. 
        $length = StringLen($m)
        If $length = 1 Then
            $m = "0" & $m
        EndIf
        
        ; Create Year folder
        DirCreate($home & "\" & $y & "\" & $m)
    Next
Next

MsgBox(0, $title, "Finished")
Exit

NOTE: The code in this article was tested using AutoIt 3.3.6.1.


Explanation
At the top there are comments within a starting tag of #cs and ending with #ce (CS = Comment Start, CE = Comment End). Other comments start with a semi-colon ";".

The script starts with some variables being declared. Variables start with a dollar sign "$". These are the parameters I am feeding into the script - they are the input. The basics of any program are input, process and output, this is a classic example. You can see I've put the range (scope) in the variables at the top. The $startY variable is for the start of the year range for example.

The code really starts at the first For...To...Next loop. First we start by creating the year folders. This means we have to loop from 1998 to 2013.

For $y = $startY to $endY Step 1

The $y is the counter, it's where the results of the loop will go. The $startY to $endY is the equivalent of 1998 to 2013 in this example (see the variables declared at the beginning). Step 1 means as it loops it will increment by one each time. This means that the code within the For and the last Next command will be executed starting at 1998, 1999, 2000, counting up to 2013.

DirCreate($home & "\" & $y)

The DirCreate function makes a folder. The variable $home is from the declared variables at the beginning of the script. I have set it to @ScriptDir - that means the same folder location where the script file is. The slash & sign adds the variable to the \ string and $y variable. The \ is needed as it is a folder delimiter. The $y is the year variable, the counter that is in the For statement. To start this command would create a folder "\1998". Below it we need to create 01 to 12 for the months...

For $m = $startM to $endM Step 1

$m is the counter here, it's the month number. The $startM and $endM are 1 to 12. It'll loop 12 times.


The month folders should be named 01, 02, 03, to 12. They can't be 1, 2, 3, etc because they will not line up properly in Windows Explorer. The script will work with just 1, 2, 3, etc. Therefore we need to add a zero to the front if the number is 1 to 9 (single digit numbers). Therefore I added this code next:

$length = StringLen($m) 
If $length = 1 Then 
     $m = "0" & $m 
EndIf

First we find out how many characters the $m variable is. Is it 1 to 9 or a two digit number? If it's a single digit number then add a zero to the front.

DirCreate($home & "\" & $y & "\" & $m)

The above will create a month folder. It will loop and create the folders 01 to 12.

MsgBox(0, $title, "Finished")

The MsgBox function shows a window on the screen with an OK button. It's just a notification the script has ended, it's not essential but nice.


Conclusion
AutoIt is an excellent way to create a little script very quickly to do any job, especially creating folders like in this example. The best thing is that you can adapt this to your needs. You could even add an interface to prompt the user to enter the years to start and end at. Or maybe add those parameters from the command prompt - it's all possible with AutoIt.



1 May 2013

AutoIt - The Scripting Language for Windows

Introduction
AutoIt is a free and excellent scripting language. It's almost a full programming language because you can do so much with it. Primarily it was designed for automating installations but it's grown and grown over the years. The best thing about it is that you write the code in a text editor (Notepad or anything you want) then compile it. Once compiled your resulting program is a standalone exe file! Yes, no DLL files to package with it!


Download and Install
http://www.autoitscript.com/

Along with AutoIt itself (it includes the compiler, samples and help files) I highly recommend you download and install the editor for it, SciTE.


SciTE
This code editor makes writing AutoIt scripts a breeze. It colour codes the commands, click a word and press F1 to see help on the command/function. It even has links on the menus so you can easily create form windows and it pastes the automatically generated code into the text editor for you.


The above is SciTE with an AutoIt script in it. You can see the colour coding, for example, the comments are in green, variables are red, etc.


An Example AutoIt Script
Here's an example of what's possible with AutoIt. It's a little script I wrote to convert text from hex to text and back again. It outputs the results to a text file and opens it in Notepad.

; Hex/Text Converter
; By Michael Gerrard
; 01/11/2011
; AutoIt 3

$title  = "Hex/Text Converter"
$input = ""
$output = ""
$outputFile = @ScriptDir & "\HexText-output.txt"

$input = InputBox($title, "Enter a hex or text:")
If @Error = 1 Then Exit

$iCheck = StringInStr($input, ":", 0, 1, 1)
If $iCheck = 3 Then ;if successful it returns 1, a colon was found and therefore it's a hex string
 _CreateText()
Else
 _CreateHex()
EndIf

; Output the result to a file
$file = FileOpen($outputFile, 2)
FileWriteLine($file, $input)
FileWriteLine($file, $output)
FileClose($file)
Run('notepad "' & $outputFile & '"', @ScriptDir)
Exit




; =========
; Functions
; =========

; Create a Hex string from Text
Func _CreateHex()

  $i = StringSplit($input, "")

  ; Make the hex numbers from each character of the text string
 For $n = 1 to $i[0]

   $hex = StringRight(Hex(Asc($i[$n])), 2)

   ; Add each char together with colons
  If $n = $i[0] Then
   $output = $output & $hex
  Else
   $output = $output & $hex & ":"
  EndIf
 Next

EndFunc


; Create a Text string from Hex
Func _CreateText()

  $i = StringSplit($input, ":")

  ; Take the hex numbers and convert them to text
 For $n = 1 to $i[0]

   $iText = Chr(Dec($i[$n]))

   ; Add each char together with colons
  $output = $output & $iText
 Next

EndFunc



What else can you do?
Read and write to the registry, to ini files easily with dedicated commands, control windows, send keystrokes to programs, interact with window controls, run command line DOS programs, pass variables to DOS programs, etc. AutoIt is really for making scripts to automate a process but you can also write GUI (Graphical User Interface) forms and other windows.


Conclusion
I've used AutoIt countless times for many years. It is powerful yet easy to learn. If you want to automate Windows this is one of the best scripting languages out there.

Recommended: 9.9 / 10