Search code examples
powershellinternet-explorerautomationservicenow

IE Automation with Powershell send ENTER Key


I am doing an IE Automation with ServiceNow where there is an option to fill the search data but there is no search button available to use the CLICK method. So I am looking for the method to enter key like {ENTER} or {~} once I filled the search data. But I am in a middle stage of PowerShell scripting and not sure how to use that.

If someone could help me with the method that would be greatly appreciate.

$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'

#Enter
$Search = $IE.Document.IHTMLDocument3_getElementsByTagName('input') | ? {$_.id -eq 'sysparm_search'}
$EnterValue = $Search.value() = $TicketNumber

Solution

  • First, you need to active IE window and bring it to front using AppActivate, then set focus to the search area using focus(). After that, you can send Enter key using SendKeys.

    I use https://www.google.com to search as an example and you can refer to my code sample below. I test it and it works well:

    [void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
    
    $ie = New-Object -ComObject 'InternetExplorer.Application'
    $ie.Visible=$true
    $ie.Navigate("https://www.google.com") #change it to your own url
    while($ie.ReadyState -ne 4 -or $ie.Busy) {Start-Sleep -m 100}
    $search=$ie.Document.getElementsByName("q")[0] #change it to your own selector
    $search.value="PowerShell" #change it to your own search value
    
    Sleep 5
    $ieProc = Get-Process | ? { $_.MainWindowHandle -eq $ie.HWND }
    [Microsoft.VisualBasic.Interaction]::AppActivate($ieProc.Id) 
    $search.focus() 
    [System.Windows.Forms.SendKeys]::Sendwait("{ENTER}");