如何使用Powershell远程向应用程序发送击键

如何使用Powershell远程向应用程序发送击键,powershell,remote-access,keystroke,wsh,Powershell,Remote Access,Keystroke,Wsh,我需要通过Powershell通过按键“q”关闭打开的应用程序窗口 我在stackoverflow()上找到了一个解决方案,它可以很好地工作,但只能在本地机器上工作: $wshell = New-Object -ComObject wscript.shell; $wshell.AppActivate('title of the application window') Sleep 1 $wshell.SendKeys('q') 问题是,我需要关闭远程机器上的窗口。我尝试了一个函数: $a =

我需要通过Powershell通过按键“q”关闭打开的应用程序窗口

我在stackoverflow()上找到了一个解决方案,它可以很好地工作,但只能在本地机器上工作:

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('q')
问题是,我需要关闭远程机器上的窗口。我尝试了一个函数:

$a = {
function Close_window {
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate(‘name of the window’)
Sleep 2
$wshell.SendKeys('q')
}
 Close_window($args)
}

$user = 'user'
$pw = 'password'
$password = ConvertTo-SecureString $pw -asplaintext -force
$credential = New-Object System.Management.Automation.PSCredential $user, $password

$servers = Get-content D:\test.txt
foreach ($server in $servers)
    {
        $session = New-PSSession -ComputerName $server -Credential $credential

        invoke-command -session $session -ScriptBlock $a
        }
我还发现:

$scriptobjects = @()
$scriptobjects += {
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate(‘Untitled - Notepad’)
Sleep 2
$wshell.SendKeys('q')
}
$scriptobjects |foreach {& $_}
但我没有在远程机器上运行它,结果总是错误的:-(

如果有人能帮我,我会很高兴的

非常感谢您的光临

Paul

当您使用powershell时,找不到使用wscript的理由。在本地,您可以使用smth,如$p=启动进程记事本-PassThru;$p.CloseMainWindow()会话是否以您传递给脚本的用户的身份运行?嗨,Jacqueline,记事本只是一个例子。我的主要目标是将键“q”发送到我的应用程序。上面的示例显示它在本地工作,但我不知道如何在远程机上运行以下代码块:$wshell=New Object-ComObject wscript.shell;$wshell.AppActivate(‘应用程序窗口的标题’)Sleep 1$wshell.SendKeys(‘q’)我需要将密钥‘q’发送到远程计算机上正在运行的应用程序/窗口。
$session = New-PSSession -ComputerName $server -Credential $credential

invoke-command -session $session -ScriptBlock {

    $p = Start-Process notepad -PassThru
    $p.CloseMainWindow()

}