You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell开发IE自动化脚本时如何向ServiceNow搜索框发送回车键

PowerShell IE自动化触发ServiceNow搜索框回车方案

优先使用方案(DOM事件触发,无焦点依赖,稳定性最高)

不需要依赖窗口焦点,直接操作页面元素触发回车事件,修改你的代码如下:

$IE = New-Object -ComObject InternetExplorer.application
$IE.FullScreen = $false
$IE.Visible = $true
$IE.Navigate($ServiceNowURL)

While ($IE.Busy -eq $true)
{
    Start-Sleep -Milliseconds 50
}

$Enter = Read-Host 'To continue press ENTER'

# 定位搜索框并赋值
$Search = $IE.Document.IHTMLDocument3_getElementsByTagName('input') | ? {$_.id -eq 'sysparm_search'}
$Search.value = $TicketNumber

# 触发回车键事件
$Search.focus()
$keyEvent = $IE.Document.createEvent("KeyboardEvent")
# 初始化回车事件,13为回车键的标准keyCode
$keyEvent.initKeyboardEvent("keydown", $true, $true, $null, 13)
$Search.dispatchEvent($keyEvent)

备选方案(SendKeys触发,仅作参考)

如果上面的DOM事件方案不生效,可使用发送系统按键的方案,注意该方案需要IE窗口处于前台激活状态:

$Search = $IE.Document.IHTMLDocument3_getElementsByTagName('input') | ? {$_.id -eq 'sysparm_search'}
$Search.value = $TicketNumber
$Search.focus()
# 发送回车按键
$wshell = New-Object -ComObject WScript.Shell
$wshell.SendKeys("{ENTER}")

注意事项

  • 优先使用DOM事件方案,不会因为操作其他窗口导致按键发送错位
  • 如果页面加载有延迟,可在定位搜索框前增加几秒等待,避免元素未加载导致报错

内容的提问来源于stack exchange,提问作者Ananthakumar Mani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 09:06:01