【问题标题】:sending arguments to running programs that expect user input automatically [duplicate]向正在运行的程序发送参数,这些程序需要用户自动输入[重复]
【发布时间】:2021-02-13 02:57:36
【问题描述】:

我正在尝试自动化备份脚本,但我使用的云备份提供商的 CLI 工具优化不佳。
首次启动时,预计会运行,然后从标准输入获取用户输入。
示例:

c:/backup> jotta.exe login
accept licence (y/n):

然后:

enter token:

如果最初的开发人员在运行程序时将这些作为参数/标志进行访问,那么最好的解决方案是,但不幸的是,情况并非如此。

有什么方法可以将“下一个输入”传递给程序或使用 PowerShell 将参数队列传递给程序?

【问题讨论】:

  • PowerShell 不控制可执行文件,它会通过调用 cmd.exe 来运行它们并由它们接管。如果提供程序确实允许传递输入,则无法通过 PowerShell 本地完成。您唯一的选择是使用 Sendkeys 到 cmd.exe 窗口。注意:虽然 sendkeys 是一个东西,但它也不是没有问题。威胁,性能方面,它可以/将更慢或更快。

标签: windows powershell


【解决方案1】:

继续我的评论。所以,像这样: 它启动 cmd.exe 和一个单独的进程,等待 3 秒,然后将定义的关键方法发送到活动的 cmd.exe 窗口。这也可以通过 VBScript/WMI 轻松完成。因此,并非特定于 PowerShell。

示例 1 - 调用 cmd.exe 直接响应提示

Clear-Host
Add-Type -AssemblyName System.Windows.Forms
Start-Process -FilePath 'cmd.exe'
Start-Sleep -Seconds 3
[System.Windows.Forms.SendKeys]::SendWait('hello world')
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
[System.Windows.Forms.SendKeys]::SendWait({Date})
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}{ENTER}")

示例 2 - 调用一个名为 cmd.exe 的 bat/cmd 文件并响应提示

Clear-Host
Add-Type -AssemblyName System.Windows.Forms
'Running bat/cmd file and responding to it.'
Start-Process -FilePath 'C:\Scripts\TestSendKeys.cmd'
Start-Sleep -Seconds 3
[System.Windows.Forms.SendKeys]::SendWait('Y')
Start-Sleep -Seconds 3
[System.Windows.Forms.SendKeys]::SendWait('{ENTER}')
'Done processing bat/cmd file.'

也仅供参考...

about_Command_Precedence

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-7

PowerShell:运行可执行文件 https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx

【讨论】:

    【解决方案2】:

    您可以尝试逐行传输到jotta.exestdin。这要求程序实际从 stdin 读取,而不是直接从键盘读取,在这种情况下 this answer 适用。

    'y', 'thetoken' | .\jotta.exe login
    

    在这里,我们将一个字符串数组传递给current directory 中的jotta.exe(用.\ 表示)。数组的每个元素都是一行输入,将排队等待应用程序从 stdin 读取。

    您也可以将两行作为一个字符串传递,嵌入换行符,例如。 g.:

    "y`nthetoken" | .\jotta.exe login
    

    或者指定jotta.exe的完整路径:

    'y', 'thetoken' | & 'C:\Program Files\JottaCLI\Jotta.exe' login
    

    (我刚刚完成了这条路径,根据需要进行更正。)

    调用运算符& 是必需的,因为我们使用的是带引号的路径。详情请见this answer

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 1970-01-01
      • 2017-08-25
      • 2021-01-25
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      相关资源
      最近更新 更多