PowerShell: Integrate Invocation of AutoIT Scripts

Although PowerShell is an incredibly powerful automation platform [primarily] for Microsoft Windows systems, it does have some gaps that other tools can fill. One of those tools is called AutoIT, which many of you are probably familiar with prior to reading this. AutoIT can handle GUI automation much more easily than PowerShell, and is therefore a desirable alternative. But, what if you need to combine PowerShell automation and some GUI automation with AutoIT? Wouldn’t it be nice to be able to simply call an AutoIT script from inside your PowerShell script, without having external dependencies to copy around alongside your PowerShell script?

Here is a simple helper function that will execute an AutoIT script in-line with your PowerShell code. I hope this makes it easier to integrate AutoIT with your existing and future PowerShell scripts. Although quite basic in its current form, this function could be enhanced to include support for firing off AutoIT scripts asynchronously, passing parameters into them, accepting output from AutoIT scripts, and so on.

[cc lines=”-1″ lang=”powershell”]
<# .Synopsis This function will invoke an AutoIT script based on an input string. .Parameter $ScriptText The ScriptText parameter is the text of the AutoIT script file that will be executed by the function. .Outputs None (for now) 🙂 .Link http://trevorsullivan.net .Author Trevor Sullivan .Date 2012-05-25 #>
function Execute-AutoItScript {
param (
[Parameter(Mandatory = $true)]
[string] $ScriptText

# Create a temporary file name
$TempFileName = ‘{0}\{1}.au3’ -f $env:TEMP, [Guid]::NewGuid().Guid.Replace(‘-‘,’ ‘);
# Write the script text to the AutoIT script file
[IO.File]::WriteAllText($TempFileName, $ScriptText);
# Get the path to AutoIT (this could be “dynamicized” 🙂
$AutoIt = ‘c:\Program Files (x86)\AutoIT3\AutoIT3.exe’;
# Invoke AutoIT with the script path
Start-Process -FilePath $AutoIt -ArgumentList $TempFileName -Wait;
# Remove the temporary AutoIT script file
Remove-Item -Path $TempFileName;

# Define the AutoIT script in a PowerShell here-string
$Script = @”
WinActivate(“XML Notepad”)

# Invoke AutoIT script defined above
Execute-AutoItScript -ScriptText $Script;