Unable to trigger click event in PowerShell - html

I want to automate a task at my work where i need to fill a form in one of our intranet sites. Basically i need to call the site, fill a specific textbox and click the save button. I am trying first to test the code on Google website but it is not working, although i am copying most of it from various sources.
The code mostly works fine. I am able to open Internet explorer, navigate to google, fill the search textbox, but i am stuck when clicking the button.
$Url
$Textbox
$Url = “www.google.com”
$Textbox=”test”
$IE = New-Object -com internetexplorer.application;
$IE.visible = $true
$IE.navigate($url)
while ($IE.Busy -eq $true)
{
Start-Sleep -Milliseconds 2000
}
$IE.Document.getElementsByname(“q”)[0].value = $Textbox
$IE.Document.getElementsByname(“btnk”)[0].Click()
while ($IE.Busy -eq $true)
{
Start-Sleep -Milliseconds 2000
}
The error message i keep getting is this:
You cannot call a method on a null-valued expression. At line:17
char:1
+ $IE.Document.getElementsByname(“btnk”)[0].Click()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
enter image description here

getElementsByname name parameter is case sensitive.
The name of the Search element is btnK and not btnk.
Change to:
$IE.Document.getElementsByname("btnK")[0].Click()

I have reproduced the problem on my machine, it seems that this behavior is related to the IE browser protected mode. Before turning on the protected mode, it will show this behavior.
To solve this issue, please turn on the Protected Mode (in my machine, I enabled the protected mode in different zones. The screenshot like this).
Besides, you could also run the PowerShell as admin.
The PowerShell script as below:
$Url
$Textbox
$Url = "www.google.com"
$Textbox="test"
$IE = New-Object -com internetexplorer.application;
$IE.visible = $true
$IE.navigate($url)
while ($IE.Busy -eq $true) { Start-Sleep -Milliseconds 2000 }
Start-Sleep -Seconds 1
$IE.Document.getElementsByName("q")[0].value = $Textbox
Start-Sleep -Seconds 1
$IE.Document.getElementsByName("btnK")[0].Click()
while ($IE.Busy -eq $true) { Start-Sleep -Milliseconds 2000 }

I've always used:
$Button_Name.RaiseEvent((New-Object -TypeName System.Windows.RoutedEventArgs $([System.Windows.Controls.Button]::ClickEvent)))
Because it works for me and I'm too lazy to look for anything else.

Related

Powershell IE Automation: How to fetch delayed loading values?

I am not sure if I mentioned the correct subject. But I will try to explain.
I am trying to do a search in a website, and then based on the result, I am trying to fetch some values.
The website is https://dotdb.com/.
When I manually go to the website, and search something (lets say 'facebook.com') and hit 'Search', I get the result which looks like this:
If you search manually, then you will notice that initially there is a loading icon on the three place (highlighted in yellow in above image),and then the values get populated.
Now, when I try to perform the same operation using Powershell IE Automation, I always see the loading icon and the value never gets set there. Therefore, I am not able to fetch the value. Here is the screenshot of the output from my powershell script:
Finally here is my powershell script:
$ie = New-Object -com internetexplorer.application
$ie.visible = $true
$ie.navigate("https://dotdb.com")
while ($ie.Busy -eq $true) {
Start-Sleep -Seconds 1;
} #wait for browser idle
($ie.document.getElementsByName("keyword") | select -first 1).value = "facebook.com"
($ie.document.getElementsByTagName('button')[2]).click()
while($ie.Busy -eq $true) {
Start-Sleep -Seconds 1;
} #wait for browser idle
Please guide me to fetch those values.
Thanks in advance!

Powershell access HTML frames

I've been trying to create a powershell script to automate something in my router's website but I can't really navigate through the sites frames and framesets, any help would be greatly appreciated!
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$ie.Navigate("http://192.168.1.1")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('userName')
$usernamefield.value = "admin"
$passwordfield = $ie.document.getElementByID('pcPassword')
$passwordfield.value = "admin"
$Link = $ie.document.getElementByID('loginBtn')
$Link.click()
$Frame1a = $ie.document.getElementByID("topFrame")
$Frame2a = $Frame1a.contentWindow
$Frame3a = $Frame2a.document
$Frame1b = $Frame3a.getElementByID('bottomLeftFrame')
$Frame2b = $Frame1b.contentWindow
$Frame3b = $Frame2b.document
$thing = $Frame3b.getElementsByTagName('a') | where-object {$_.innerText -eq 'Wireless'}
This is the code I have so far, but when it gets to $Frame1b = $Frame3a.getElementByID('bottomLeftFrame') I get an error message saying: "You cannot call a method on a null-valued expression."
After I get this frame thing to work, I'd need it to click a hyperlink, if anyone knows how to do that please tell me, I've tried before but it didn't work. I've also tried different languages before, python, VBS, but I got the furthest with powershell.
Thanks for the attention!
I had similar issue in the past. I solved it like this:
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true # Make it visible
$ie.Navigate("http://192.168.1.1")
While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}
$usernamefield = $ie.document.getElementByID('userName')
$usernamefield.value = "admin"
$passwordfield = $ie.document.getElementByID('pcPassword')
$passwordfield.value = "admin"
$Link = $ie.document.getElementByID('loginBtn')
$Link.click()
start-Sleep -Milliseconds 500
#Click Wireless
$oFrameLeft=$ie.document.parentwindow.frames['bottomLeftFrame'].document
$oWireless = $oFrameLeft.IHTMLDocument3_getElementsByTagName('a') | where-object {$_.innerText -eq 'Wireless'}
$oWireless.click()

button click on website using powershell

i am adding user id and password to website and trying to login to site. in below code i am not able to click on the Login button i tried click submit but not able to click. can any one please help me
$username = "abcd"
$password = "abc"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$true
$ie.navigate("https://wss.mahadiscom.in/wss/wss?uiActionName=getCustAccountLogin")
while($ie.ReadyState -ne 4) {start-sleep -m 100}
$ie.document.getElementById("loginId").value= "$username"
$ie.document.getElementById("password").value = "$password"
$fs = $ie.document.getElementById("loginButton")
$fs.click()
Instead of native getElementById method, use IHTMLDocument3_getElementById:
$username="myname"
$password="mypass"
$url = "http://wss.mahadiscom.in/wss/wss?uiActionName=getCustAccountLogin"
$ie = New-Object -com InternetExplorer.Application
$ie.visible = $true
$ie.navigate($url)
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
$ie.document.IHTMLDocument3_getElementById("loginId").value = $username
$ie.document.IHTMLDocument3_getElementById("password").value = $password
$ie.document.IHTMLDocument3_getElementById("loginButton").click()
It will show an alert stating "Login Name and Password combination is incorrect.".
It's working on my machine having IE11 and WIN10. There are 3 important changes in above code:
Using http rather than https because of IE problem with certificate of that site at the time which I tried the site.
Checking Busy property of IE to check if IE is busy, then wait for it.
Using IHTMLDocument3_getElementById instead of getElementById.

powershell IE automation href issue

I am trying to access Jtrac webpage using powershell. i am able to login into but i am unable to access SEARCH button which href link.
$Url = “http://kbserver/workflow/app/login”
enter code here`$Username=”XXXXX”
enter code here`$Password=”XXXXX”
$IE = New-Object -com internetexplorer.application;
$IE.visible = $true;
$IE.navigate($Url);
while ($IE.Busy -eq $true)
{
Start-Sleep -Milliseconds 2000;
}
$Login = $IE.document.getElementById("loginName3").value = "$Username"
$Login = $IE.Document.getElementById(“password12”).value= "$Password"
$Login = $IE.Document.getElementsByTagName("input") | where-object {$_.type -eq "submit"}
$Login.click();
while ($IE.Busy -eq $true)
{
Start-Sleep -Milliseconds 5000;
}
$Login = $IE.Document.getElementsByTagName("a") | where {$_.href -eq "'?wicket:interface=:2:table:dashboardRows:3:dashboardRow:search::ILinkListen er::'"}
$Login.click();
Error which i am getting is
You cannot call a method on a null-valued expression.
At C:\Users\Dinesh\Webbb.ps1:20 char:13
+ $Login.click <<<< ();
+ CategoryInfo : InvalidOperation: (click:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
<a href="?wicket:interface=:2:table:dashboardRows:3:dashboardRow:search::ILinkListener::">
<img title="SEARCH" src="../resources/search.gif"> </a>
It looks like you have a typo in line 19, ILinkListen er:: at the end of your where instead of ILinkListener::. Where isn't finding anything to match, so it returns null, and that's how you get your null-valued $Login object.
Edit: Your problem is still line 19, you should print out $IE.Document.getElementsByTagName("a") and verify that it's actually returning what you expect, because your where filter is not matching anything and returning $null to $Login.
Edit2: went to a website and grabbed all the hrefs and took a look, powershell removes the "" from the hrefs.
you should have $IE.Document.getElementsByTagName("a") | where {$_.href -eq "?wicket:interface=:2:table:dashboardRows:3:dashboardRow:search::ILinkListener::"} instead.
Edit 3: Your second issue can be solved with regex using the -match operator instead of -eq (-eq does not really work if the item you are checking is dyanmic ).
Like this:
$IE.Document.getElementsByTagName("a") | where {$_.href -match "\?wicket:interface=:\d"}
This regex will return anything that containts "?wicket:interface=:digit".
One digit is the best option here since it will keep growing on refresh, assuming nothing else on the page matches that this should be good.

using powershell to click a link on a web page and then pass credentials

I am trying to test our a web page we built that has a temp ssl cert, the issue is that when I goto the page I get the IE security warning that the ssl cert is invalid, with two links one to close the page, and the other to proceed to the page. I was able to use powershell to open IE and click the link on the ssl warning page, but now I need to populate the username and password input boxes and then click the login button.
$url = "res://ieframe.dll/invalidcert.htm?SSLError=50331648#https://10.2.2.1:8050/showme.do"
$ie = New-Object -comobject InternetExplorer.Application
$ie.visible = $true
$ie.silent = $true
$ie.Navigate( $url )
while( $ie.busy){Start-Sleep 1}
$secLink = $ie.Document.getElementsByTagName('A') | Where-Object {$_.innerText - eq 'Continue to this website (not recommended).'}
$secLink.click()
$ie.Document.getElementsByType("input") | where { $.Name -eq "j_username" }.value = "user"
$ie.Document.getElementsByName("input") | where { $.Name -eq "j_password" }.value = "password"
$loginBtn = $ie.Document.getElementsById('input') | Where-Object {$_.Type -eq 'button' -and $_.Value -eq 'LoginButton'}
$loginBtn.click()
So right now the page opens but the input fields are not populated or the button clicked, Do I need some kind of loop or while statement?
thanks
You need to wait until the page finishes loading when you've clicked on a link.
$url = "res://ieframe.dll/invalidcert.htm?SSLError=50331648#https://10.2.2.1:8050/showme.do"
$ie = New-Object -comobject InternetExplorer.Application
$ie.visible = $true
$ie.silent = $true
$ie.Navigate( $url )
while( $ie.busy){Start-Sleep 1}
$secLink = $ie.Document.getElementsByTagName('A') | Where-Object {$_.innerText - eq 'Continue to this website (not recommended).'}
$secLink.click()
while( $ie.busy){Start-Sleep 1}
$ie.Document.getElementsByType("input") | where { $.Name -eq "j_username" }.value = "user"
$ie.Document.getElementsByName("input") | where { $.Name -eq "j_password" }.value = "password"
$loginBtn = $ie.Document.getElementsById('input') | Where-Object {$_.Type -eq 'button' -and $_.Value -eq 'LoginButton'}
$loginBtn.click()
Write-Output "- Kill all IE windows"
get-process iexplore | stop-process -Force
Start-Sleep -s 1
function that open IE for a given url and a password retrieved from encrypted file
function OpenIE([string]$url, [string]$p)
{
Open Internet Explorer with a given url
$wshell = New-Object -com WScript.Shell
$wshell.Run("iexplore.exe $url")
Start-Sleep 1
Send user credentials to IE
$wshell.sendkeys("+{TAB}")
$wshell.sendkeys("username")
$wshell.sendkeys("{TAB}")
$wshell.sendkeys($p)
$wshell.sendkeys("{ENTER}")
}
$credentialsfile = "C:\temp\credfile.txt"
Check if credential file exists
if (Test-Path $credentialsfile)
{
Retrieve the credentials from an encrypted file
$encp = get-content $credentialsfile | convertto-securestring
$ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($encp)
$p = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)
remove-variable encp,ptr
}else{
Request credentials and save to encrypted file
$creds = Get-Credential –credential DOMAIN\user
$encp = $creds.password
$encp |ConvertFrom-SecureString |Set-Content $credentialsfile
}
Write-Output "- open IE"
OpenIE "http://www.yoururlhere.com" $p
You would probably find it a lot easier to work with something like the (free) Windows Automation module for PowerShell up on codeplex:
WASP is a PowerShell snapin for Windows Automation tasks like
selecting windows and controls and sending mouse and keyboard events.
We have automation cmdlets like Select-Window, Select-Control,
Send-Keys, Send-Click, Get-WindowPosition, Set-WindowPosition,
Set-WindowActive, Remove-Window ... etc.
Our goal is to enable you to accomplish most Windows GUI Automation
scripting from inside PowerShell, without resorting to specialized
(and expensive) scripting tools.
http://wasp.codeplex.com/