0

I'm trying to emulate the user actions to open and close an application using powershell. Using Sendkeys I'm able to navigate to the required tab in the dialog box. I would like to know how to capture the value of the element which is currently in focus and write it to a variable.

Expected output: In the image, assume the TAB stroke has taken to the "FILE NAME" field. Now I would like read and store the value "Book1" in a variable $FILE_NAME for further processing. In the image, assume the TAB stroke has taken to the  field. Now I would like read and store the value "Book1" in a variable $FILE_NAME for further processing.

Vijay
  • 15
  • 2

2 Answers2

1

Sendkeys (built into Windows and as been around for decades) or AutoIT or Selenium is what you should use for UI automation. For the target like Excel, you need to know the Excel DOM to work with it.

See this SO discussion as well, since it is similar to your ask.

Send Keys in Powershell alt+n {TAB} {ENTER}

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait("%n{TAB}{ENTER}")

Point of note:

Sendkeys has its issues, which is why you'll see folks complain about it, but it does work, as long as you understand its limitations and performance considerations.

See also the PowerShell Excel module(s):

Find-Module -Name '*Excel*' | Format-Table -AutoSize

PowerShell and Excel: Yes, They Work Together: https://adamtheautomator.com/powershell-excel-tutorial

Videos: https://www.youtube.com/results?search_query=powershell+sendkeys+ms+excel

postanote
  • 15,138
  • 2
  • 14
  • 25
0

Use an UI automation tool might work better as @postanote suggests. Anyway, one can use Get-Clipboard and Windows' default clipboard shortcut, ctrl+c. Like so,

... # switch to Excel's dialog first
# Copy with ctrl+c
[System.Windows.Forms.SendKeys]::SendWait('^{c}')
# Save clipboard contents
$d = Get-Clipboard
write-host "From clip: $d"

# Output
From clip: Book1.xlsx
vonPryz
  • 22,996
  • 7
  • 54
  • 65