Powershell - Interact with executable's comman

2019-07-31 14:18发布

I need to automate some tasks against a legacy application. It doesn't have an API, but the vendor offers a .exe I can run to perform various tasks against the application.

I can call the .exe from within PowerShell just fine, but after calling it it prompts for the following input:

Do you agree to the license: YES
User name: myuid
Password: SuperSecretPassword`

I can run this interactively from the command prompt just fine and manually enter the requested input as prompted, but I need to automate this in a script. The .exe doesn't accept any command line parameters for this either(it's an old app), the only parameters I can pass are the commands I want to execute against the application. The .exe is only command line based with no GUI, so GUI automation tools aren't an option either.

I could do this easily with expect in a *nix shell, however given that I have a .exe I need to run, that's out of the question. There doesn't appear to be an "expect" equivalent in Windows, so I'm curious if this can be accomplished in PowerShell?

Note: For Windows scripts I prefer PowerShell, but could utilize VBScript if necessary.

1条回答
Lonely孤独者°
2楼-- · 2019-07-31 15:06

If I remember correctly, if it's just one line you can pipe a string to an exe eg. "asdf" | example.exe, but it's multiple lines of input you might need to use SendKeys

Add-Type -AssemblyName 'System.Windows.Forms'
$ID = (Start-Process example.exe -PassThru).id 
Sleep 1
Add-Type -AssemblyName Microsoft.VisualBasic 
[Microsoft.VisualBasic.Interaction]::AppActivate([Int32]$ID)
[System.Windows.Forms.SendKeys]::SendWait("YES~")
[System.Windows.Forms.SendKeys]::SendWait("myuid~")
[System.Windows.Forms.SendKeys]::SendWait("SuperSecretPassword~")
查看更多
登录 后发表回答