Powershell 中的 SendKeys 方法

yaz*_*zan 7 telnet powershell

我有自动 telnet 服务器的批处理文件,我想用 PowerShell 做同样的事情

名为 Script.bat 的批处理文件:

:: Open a Telnet window
 start telnet.exe 10.84.10.85
:: Run the script
 cscript SendKeys.vbs
Run Code Online (Sandbox Code Playgroud)

名为 SendKeys.vbs 的命令文件:

set OBJECT=WScript.CreateObject("WScript.Shell")
 WScript.sleep 1000
 OBJECT.SendKeys "myPassword{ENTER}"
 WScript.sleep 1000
 OBJECT.SendKeys "7{ENTER}"
 WScript.sleep 1000
 OBJECT.SendKeys "1{ENTER}"
 WScript.sleep 1000
 OBJECT.SendKeys "{ENTER}"
 WScript.sleep 1000
 OBJECT.SendKeys "{ENTER}"
 WScript.sleep 1000
 OBJECT.SendKeys "Y{ENTER}"
 WScript.sleep 3000
 OBJECT.SendKeys ""
Run Code Online (Sandbox Code Playgroud)

wp7*_*8de 16

PowerShell 没有内置功能来模拟击键。

实际上,您有两个选择:COM-Automation 和 Interop。

  1. 通过 COM 发送密钥

就像在 VB(S) 中一样,您可以创建一个 Shell-Object 和 SendKeys。这是执行此操作的 PowerShell 方法。

$wshell = New-Object -ComObject wscript.shell;
$wshell.SendKeys('a')
Run Code Online (Sandbox Code Playgroud)

如果您想向窗口发送按键,您必须先激活它:

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('~')
Run Code Online (Sandbox Code Playgroud)

某些击键具有特殊的变量,例如用于 RETURN 的 ~。是一个完整的列表。
激活窗口后,通常需要等待一秒钟,直到它有响应,否则它会将密钥发送到 PowerShell 窗口,或者发送到任何地方。脚本主机的 SendKeys 方法可能不可靠,但幸运的是有更好的方法。

  1. 通过互操作发送密钥

与在 C# 中一样,您可以在 PowerShell 中使用.NET Framework 中的SendWait方法。

[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("x")
Run Code Online (Sandbox Code Playgroud)

如果你想激活一个窗口,可以这样做:

[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[Microsoft.VisualBasic.Interaction]::AppActivate("Internet Explorer - Windows")
Run Code Online (Sandbox Code Playgroud)

要睡眠,您可以使用Start-Sleep Cmdlet。

关于您的原始问题,我建议以下解决方案:

# Open a Telnet window
Start-Process telnet.exe -ArgumentList 10.84.10.85
# Run the keystrokes
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('myPassword{ENTER}')
Start-Sleep 1
[System.Windows.Forms.SendKeys]::SendWait('7{ENTER}')
Start-Sleep 1
[System.Windows.Forms.SendKeys]::SendWait('1{ENTER}')
Start-Sleep 1
[System.Windows.Forms.SendKeys]::SendWait('{ENTER}')
Start-Sleep 1
[System.Windows.Forms.SendKeys]::SendWait('{ENTER}')
Start-Sleep 1
[System.Windows.Forms.SendKeys]::SendWait('Y{ENTER}')
Start-Sleep 1
[System.Windows.Forms.SendKeys]::SendWait('')
Run Code Online (Sandbox Code Playgroud)

警告:如果您使用此方法发送密码,请格外小心,因为在调用AppActivate和调用之间激活不同的窗口SendKeys会导致密码以纯文本形式发送到该不同的窗口(例如,您最喜欢的信使)!