How Do You Automate a Process That Involve a GUI Operation with Powershell?

Question:  How Do You Automate a Process That Involve a GUI (e.g., to save an .xps or .oxps file) Operation with Powershell?  You do not want any part to be interactive.

Solution:  This applies to PowerShell version 4 and above.  This will save the content of c:\temp\contint.txt to goodName.xps in the default folder (often the user's Documents folder) without needing to attend to the process.

# These three lines (starting with "Add...", "set...", and "start..." ensure the XPS Viewer is functional:
Add-WindowsFeature XPS-Viewer  #this ensures the server has XPS viewer as a printer driver
set-service spooler manual  #if the printer spooler is disabled, this will not work
start-service spooler       #if the printer spooler is not working, the automation will not work

# These next lines print a file:
start-process -FilePath C:\temp\contint.txt -Verb print
start-sleep 1 #wait one second for the application to open
[System.Windows.Forms.SendKeys]::SendWait({"goodName"})  # This input a name into the GUI
[System.Windows.Forms.SendKeys]::SendWait({'~'})  # This saves the file with issuing "Enter"

# To learn more about the PowerShell-to-keyboard mapping, use this link:
http://www.vexasoft.com/pages/send-keyboardinput
# It is possible to use SendKeys to tab up, change the path where the .xps file is saved, and tab down to finally save it.
# The above code is a simple example of something that may be useful.
# To save to a .pdf, try this link.

Leave a comment

Your email address will not be published. Required fields are marked *