首页 > 解决方案 > 如何使用powershell将键/输入发送到没有登录用户的正在运行的进程?

问题描述

我在使用 powershell 自动安装应用程序的一部分时遇到问题。安装的一部分是运行带有参数的命令行工具并输入凭据以访问数据库。这应该在不登录的情况下完成。为此,我一直在使用计划任务在系统启动时启动我的脚本。

我一直在尝试通过使用 AppActivate 和 SendWait 将凭据发送到窗口来使这个特定步骤正常工作。这不起作用,因为如果我使用任务调度程序,则没有交互式窗口。

这是我一直在使用的当前脚本。例如,如果我使用 RunOnce 键,它就可以工作。

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")

powershell.exe add-type -AssemblyName microsoft.VisualBasic

add-type -AssemblyName System.Windows.Forms

$parms = 'create instance'

Start-Process "app.exe" -ArgumentList $parms -WorkingDirectory "C:\app\app.exe"

start-sleep -Milliseconds 1000

[Microsoft.VisualBasic.Interaction]::AppActivate("C:\app\app.exe")

[System.Windows.Forms.SendKeys]::SendWait("username")

start-sleep -Milliseconds 1000

[Microsoft.VisualBasic.Interaction]::AppActivate("C:\app\app.exe")

[System.Windows.Forms.SendKeys]::SendWait("password")

此脚本由任务调度程序运行的另一个脚本调用。现在它失败了:

Exception calling "AppActivate" with "1" argument(s): "Process '{0}' was not found."

和:

Exception calling "SendWait" with "1" argument(s): "Access is denied"

这是由于无法访问该窗口。

有没有办法在不需要活动窗口的情况下将用户名和密码发送到进程?从我所见,powershell似乎不支持它,但我仍然希望有办法。也许使用句柄?我不能使用任何应用程序,如 AutoHotkey 或 AutoIt。

标签: powershellscheduled-taskssendkeys

解决方案


尝试这个,

    $proc = Get-process | where {$_.path -eq "C:\app\app.exe"}
    [Microsoft.VisualBasic.Interaction]::AppActivate($Proc.id)

推荐阅读