Powershell - Interact with executable's command line prompts?

て烟熏妆下的殇ゞ 提交于 2019-12-11 02:30:57

问题


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:


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~")


来源:https://stackoverflow.com/questions/43852056/powershell-interact-with-executables-command-line-prompts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!