Powershell select item in dropdown list using internetexplorer.application - powershell

I am attempting to select a dropdown item via Powershell. Its using Javascript. So far I'm only achieved to login and get a bunch of methods by getting the Element. See below.
# Create an ie com object
$ie = New-Object -com internetexplorer.application;
$ie.visible = $true;
$ie.navigate($url);
# Wait for the page to load
while ($ie.Busy -eq $true){ Start-Sleep -Milliseconds 1000; }
# Login
Write-Host -ForegroundColor Green "Attempting to login.";
# Add login details
try
{
$ie.Document.IHTMLDocument3_getElementsByName("user") = $username
$ie.Document.IHTMLDocument3_getElementsByName("pass") = $password
$ie.Document.IHTMLDocument3_getElementsByName("submit")
Do{Start-Sleep -Milliseconds 100}While($ie.Busy -eq $True)
}
catch
{
$_.Exception.Message
}
#get dropdown elementarray
$ie.Document.IHTMLDocument3_getElementById('contentPlaceHolderId')
#get methods
$ie.Document.IHTMLDocument3_getElementById('contentPlaceHolderId') | gm
Does anybody know how to select a specific element in the placeholder? Methods are too many to fit in the post.
Thanks in advance.

For anybody else the answer is:
($ie.Document.IHTMLDocument3_getElementById('$contentPlaceHolderId') | Where-Object { $_.innerHTML -eq '$DropDownElementName' }).selected = $true
Clicking a button is:
$ie.Document.IHTMLDocument3_getElementById('$button').click();

Related

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
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}");

Download an Excel document from website with Powershell

recently I began to learn PowerShell to automate my job tasks.
So I want to access a web page and click on a button that download automatically an Excel file. This is the button that I want to click on:
<div class="NormalButton">
<a class="ActiveLink" title="Excel" alt="Excel" onclick="$find('ctl32').exportReport('EXCELOPENXML');" href="javascript:void(0)" style="padding:3px 8px 3px 8px;display:block;white-space:nowrap;text-decoration:none;">Excel</a>
</div>
This would be my PowerShell script:
$ie = New-Object -com "InternetExplorer.Application"
$ie.Navigate("http://test.test/")
$ie.Visible = $true
$link = $ie.Document.getElementsByTagName('a') | Where-Object {$_.onclick -eq "$find('ctl32').exportReport('EXCELOPENXML');"}
$link.click()
If I try to run it from the console I receive the error "You cannot call a method on a null-valued expression."
If its useful I'm using PowerShell 4.0 and the webpage has a delay until the report is loaded.
I have completed it by the following code:
[void][System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$url = "https://webpage.com"
$ie = New-Object -com internetexplorer.application
$ie.navigate($url)
$ie.StatusBar = $false
$ie.ToolBar = $false
$ie.visible = $true
#Get Excel
Start-Sleep -s 40
$btnExcel = $ie.Document.links | where-object { $_.outerText -eq 'Excel' -and $_.innerText -eq 'Excel' }
$btnExcel.click()
# Get Internet Explorer Focus
Start-Sleep -s 5
[Microsoft.VisualBasic.Interaction]::AppActivate("internet explorer")
[System.Windows.Forms.SendKeys]::SendWait("{F6}");
[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("{ENTER}");
# Get Internet Explorer Focus
Start-Sleep -s 1
[Microsoft.VisualBasic.Interaction]::AppActivate("internet explorer")
[System.Windows.Forms.SendKeys]::SendWait("^{F4}");
Thank you all for you time :)
I Think the Your problem is because you are using Double Quotes which powershell threat it like variable and Try to expand it, so try to change it to Single quote, from:
$link = $ie.Document.getElementsByTagName('a') | Where-Object {$_.onclick -eq "$find('ctl32').exportReport('EXCELOPENXML');"}
to:
$link = $ie.Document.getElementsByTagName('a') | Where-Object {$_.onclick -eq '$find('ctl32').exportReport('EXCELOPENXML');'}
Also, you can change the -eq to -match and take just a portion of it like:
$_.onclick -match '$find('ctl32').exportReport'
For more information see: About Quoting Rules

Cannot close Internet Explorer with Powershell after form submission

I open a page, fill in fields, click submit. The submit does do a redirect. When I try $ie2.quit() it won't close the window. Any ideas?
$ie2 = New-Object -com InternetExplorer.Application
$ie2.visible=$true
$ie2.navigate("http://localhost/useradd.jsp")
start-sleep -seconds 3
$ie2.Document.getElementById("UserId").value = "test1"
$ie2.Document.getElementById("UserName").value = "test1 user"
$ie2.Document.getElementById("UserPassword").value = "12345$"
$submitButton = $ie2.document.getElementsByTagName("input")
Foreach($element in $submitButton )
{
#look for this field by value this is the field(look for screenshot below)
if($element.value -eq "Add"){
Write-Host $element.click()
}
$ie2.quit()
Try to add something like while ($ie2.Busy) { Start-Sleep -Seconds 1 } before the $ie2.quit() Statement to make sure, the COM Object is repsonsive.

Read text from new window with powershell

I'm trying to make a powershell script that would open up a new IE window from javascript link and I would like to read a text from that new window. So far, the script would only read the content from original IE window and I'm not sure how to get the script to read content off from new IE page.
$ie = new-object -com InternetExplorer.Application
$ie.navigate("https://www.testsite.com/")
do {sleep 1} until (-not ($ie.Busy))
$ie.visible = $true
$doc = $ie.document
if ($ie.document.documentelement.innerText.Contains('Welcome') -eq "True") {
"Site is RUNNING"
} else {
"Site is STOPPED"
}
$link = #($ie.Document.getElementsByTagName('A')) | Where-Object {$_.innerText -eq 'Click here for new site'}
$link.click()
if ($ie.document.documentelement.innerText.Contains('New Page') -eq "True") {
"Site is RUNNING"
} else {
"Site is STOPPED"
}
New window pops up after $link.click(), and I don't know how to read anything from the new window. I could read the text from original www.test.com/ page but not from the new page.
Thank you.
PT
You can use the following code to iterate over all IE windows/tabs and select the one with the title you're looking for:
$title = '...'
$ie2 = (New-Object -COM 'Shell.Application').Windows() | ? {
$_.Name -eq 'Windows Internet Explorer' -and $_.LocationName -eq $title
}

Powershell script to do web UI Automation not working

I have this script to launch IE, navigate to a page and search for some text:
$ie = new-object -com "InternetExplorer.Application"
$ie.Visible = $true
$ie.Navigate("http://www.google.com")
$doc = $ie.Document
if ($doc -eq $null)
{
Write-Host "The document is null."
return
}
$tb1 = $doc.getElementsByName("q") # a text box
$tb1.value = "search text";
$btn = $doc.getElementsByName("btnG")
$btn.click()
I save this as a ps1 file and run it from the command line... but the document object returned by $ie.Document is always null.
What am I doing wrong?
Also, when I run the script line by line in interpreter mode, the document is returned, but the next line $tb = $doc.getElementsByName("q") errors with this: Property 'Value' cannot be found on this object; make sure it exists and is settable.
How do I set the value of the text box, then?
You need to check if IE was done loading the page before $doc assignment. For example,
while ($ie.busy) {
#Sleep a bit
}
I tried the same code for entering the search text and button click but that did not work. So, ended up modiying your code to
$ie = new-object -com "InternetExplorer.Application"
$ie.Visible = $true
$ie.Navigate("http://www.google.com")
While ($ie.Busy) {
Sleep 2
}
$doc = $ie.Document
$btns = $doc.getElementsByTagName("input")
$SearchText = $btns | ? { $_.Name -eq "q" }
$SearchText.value = "search text"
$SearchButton = $btns | ? { $_.Name -eq "btnG" }
$SearchButton.click()
I believe there are two issues that I can see. First, Ravikahth's suggestion to add the ability to wait for the page to finish loading is important. If you do not wait for the page to load (i.e. $ie.busy -eq $false), then you will not get the full document.
Second, for whatever reason, Google decided to add multiple input fields with the name of "q." You can add a second condition to Ravikanth's query as stated below:
$SearchText = $btns | ? { $_.Name -eq "q" -and $_.Type -eq "text"}