简体   繁体   中英

How to send a keystroke to an application remotely with Powershell

I need to close an open application windows with a keystroke "q" via Powershell.

I found a solution here on stackoverflow ( How to perform keystroke inside powershell? ) which works perfectly fine but only on a local machine:

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('q')

Problem is, I need to close that windows on a remote machine. I tried it with a function:

$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
        }

I also found this:

$scriptobjects = @()
$scriptobjects += {
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate(‘Untitled - Notepad’)
Sleep 2
$wshell.SendKeys('q')
}
$scriptobjects |foreach {& $_}

but I did not manage it to run on a remote machine, the result is always FALSE :-(

I would be happy if someone could help me with this!

Many thanks in advance
Paul

$session = New-PSSession -ComputerName $server -Credential $credential

invoke-command -session $session -ScriptBlock {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM