3

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

Community
  • 1
  • 1
Paul Smith
  • 499
  • 2
  • 6
  • 17
  • cant see a reason to use wscript when you have powershell. localy youd have smth like $p = Start-Process notepad -PassThru; $p.CloseMainWindow() – Jaqueline Vanek Dec 13 '15 at 21:06
  • Is the session running as you user you are passing to the script? – Matt Dec 13 '15 at 21:49
  • Hi Jacqueline, Notepad is just an example. My main goal is to send the key 'q' to my application. The above example shows that it does work locally but I don't know how to run the following code block on a remote machine: $wshell = New-Object -ComObject wscript.shell; $wshell.AppActivate('title of the application window') Sleep 1 $wshell.SendKeys('q') – Paul Smith Dec 14 '15 at 10:35

1 Answers1

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

invoke-command -session $session -ScriptBlock {

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

}
Jaqueline Vanek
  • 1,100
  • 10
  • 20