Skip to content

Instantly share code, notes, and snippets.

@DBremen
Created February 2, 2021 16:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DBremen/0e73989fbe49a538331a8c36b9f905ae to your computer and use it in GitHub Desktop.
Save DBremen/0e73989fbe49a538331a8c36b9f905ae to your computer and use it in GitHub Desktop.
UIAutomation PowerShell example
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
$calc = [Diagnostics.Process]::Start('calc')
#wait for the UI to appear
$null = $calc.WaitForInputIdle(5000)
sleep -s 2
$calcWindowId = ((Get-Process).where{$_.MainWindowTitle -eq 'Calculator'})[0].Id
$root = [Windows.Automation.AutomationElement]::RootElement
$condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, $calcWindowId)
$calcUI = $root.FindFirst([Windows.Automation.TreeScope]::Children, $condition)
function FindAndClickButton($name){
$condition1 = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty, "Button")
$condition2 = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, $name)
$condition = New-Object Windows.Automation.AndCondition($condition1, $condition2)
$button = $calcUI.FindFirst([Windows.Automation.TreeScope]::Descendants, $condition)
$button.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
}
#get and click the buttons for the calculation
FindAndClickButton Five
FindAndClickButton Plus
FindAndClickButton Nine
FindAndClickButton Equals
#get the result
$condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::AutomationIdProperty, "CalculatorResults")
$result = $calcUI.FindFirst([Windows.Automation.TreeScope]::Descendants, $condition)
$result.current.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment