PowerShell SendKeys到InternetExplorer ComObject

时间:2015-04-09 06:10:31

标签: shell powershell sendkeys

这是我发现的一个方法,它将IE ComObject窗口带到前台并使用SendKeys。

如何使用此方法发送一系列按键?

$ie = New-Object -ComObject InternetExplorer.Application
$ie.navigate("www.google.com")
do {sleep 1} until (-not ($ie.Busy))
Add-Type -AssemblyName System.Windows.Forms
Add-Type @"
 using System;
 using System.Runtime.InteropServices;
 public class StartActivateProgramClass {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
 public static extern bool SetForegroundWindow(IntPtr hWnd);
 }
"@
$hWnd = $ie.HWND
$ie.Visible = $true
[void] [StartActivateProgramClass]::SetForegroundWindow($hWnd)
[System.Windows.Forms.SendKeys]::SendWait("a 2")

2 个答案:

答案 0 :(得分:1)

您必须加载Windows窗体组件才能使用SendKeys。 这是一个例子

[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")

$ie=new-object -com "internetexplorer.application"
$ie.visible=$true
$ie.navigate("http://someURI")

#waiting for my form 
while( ($ie.document.body.getElementsbytagname("input") |?{$_.type -eq 'file'}) -eq $null){
        start-sleep -milliseconds 100
    }
# give the focus to ie
[Microsoft.VisualBasic.Interaction]::AppActivate("internet explorer")

#send keys 
[System.Windows.Forms.SendKeys]::Sendwait("{TAB}");   
[System.Windows.Forms.SendKeys]::Sendwait(" ");   
start-sleep 1
[System.Windows.Forms.SendKeys]::Sendwait($file);         
[System.Windows.Forms.SendKeys]::Sendwait("{TAB}");
[System.Windows.Forms.SendKeys]::Sendwait("{ENTER}");

我自己尝试自动化IE以进行一些性能测试,但SendKeys不是一种安全的方法,想象一个应用程序窃取焦点,然后所有的密钥都发送到这个应用程序而不是IE。使用Selenium项目将是我认为的方式

答案 1 :(得分:0)

我想看看.NET sendkey方法是否会点击一个带有我编写的脚本的按钮,以自动登录到https:网站。(最后我将安排任务调度程序并让它在每天的某个时间自动化)。我使用.NET程序集中的{Enter}发送密钥。它对我有用,所以我决定分享它会帮助某人。

您可能需要检查您的html文档以查看TagName的具体类型并进行相应编辑。

$ IE = new-object -com Internetexplorer.application

$IE.navigate2("https://Yourwebsite.com")
$IE.visible=$true
do { sleep 15 }
while ( $IE.busy )

$Link=@($IE.Document.getElementsByTagName("input.")) | where-object {$_.type     -eq "submit"}
$click=$Link.[System.Windows.Forms.SendKeys]::Sendwait("{ENTER}");
$click

****您必须在Powershell脚本中添加.NET命名空间才能使用命名空间,否则它将为您提供错误****

实施例。 [void] [System.Reflection.Assembly] :: LoadWithPartialName(“System.Windows.Forms”)