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