远程调用时 Powershell SendKeys 访问被拒绝

Powershell SendKeys Access Denied When Invoked Remotely

我正在测试一个监听远程机器按键的程序,所以我需要以某种方式生成它们,最好只使用 powershell 核心。

当我尝试通过 invoke-command 在远程计算机上使用 SendKeys 时,我遇到访问被拒绝(win32 异常或 dotnetmethod 异常),即使凭据已提供给具有管理员权限的脚本并且它在本地工作正常。

我用这种方式 运行 编写了很多脚本,而这个脚本是唯一失败的脚本(并且在所有操作系统上都以相同的方式失败)

例如

$script =
{    
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait($item);
}

invoke-command -computername $machine -scriptblock $script -credential $cred

SendInput 看起来可能是一个很有前途的替代品,但我一直无法找到适合我的示例。

原来问题是由于无法访问 windows 用户会话。

我通过在远程机器上创建计划任务并调用 powershell 脚本解决了这个问题。这样脚本 运行s 在用户会话中。

否则它似乎 运行 在无法调用键盘和鼠标 API 的无图形用户界面会话中。

我在通过远程会话发送键盘键时遇到了类似的问题。 为了克服这个问题,我使用了 PSexec 工具。 https://docs.microsoft.com/en-us/sysinternals/downloads/psexec 将要执行的脚本复制到远程计算机,然后使用 PsExec 工具从远程计算机运行 脚本。

这是语法。我正在使用 PsExec 工具从另一台 windows 机器 运行 将位于远程主机 C 驱动器中的脚本 "testscript.ps1" 连接起来。

PsExec.exe \\RemoteHostName -u Domain\UserName -p -i Powershell -noExit -Command "& Invoke-Command -ScriptBlock {C:\testscript.ps1;stop-进程 $PID}