Select from auto-complete options - html

I want to open next page in Powershell script by selecting first option in Auto-complete.
For example. When I open www.healthkartplus.com and type "Sporanox (100mg)". I want to select first option in Auto-complete.
I do not know how to select option from auto-complete so what I am trying is simply get first link on next page.
$ie = New-Object -COMObject InternetExplorer.Application
$ie.visible = $true
$site = $ie.Navigate("https://www.healthkartplus.com/search/all?name=Sporanox (100mg)")
$ie.ReadyState
while ($ie.Busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 100 }
$link = $null
$link = $ie.Document.get_links() | where-object {$_.innerText -eq "Sporanox (100mg)"}
$link.click()

Related

How do I dynamically insert a string into a text file in PowerShell?

The text is an html file. The line I am interested in looks something like:
<td>INC1234</td><td>INC1235</td><td>INC1236</td>
The INC numbers are different from file to file. I'd like to parse through the line by saying something like:
if like <td>INC, then concatenate '<td><a href="https://www.website.com/=' + INC# + '>"
To give an output like:
<td><a href="https://www.website.com/=INC1234>INC1234</a></td><td><a href="https://www.website.com/=INC1235>INC1235</a></td><td><a href="https://www.website.com/=INC1236>INC1236</a></td>"
EDIT1: Ok, if I do something like:
$parse = (-split (Get-Content -Raw C:\Temp\report.txt) -match '<td>INC')
$parse
It will find the characters, but it will return the entire line rather than looking for more that match the 'INC'. Presumably because they all reside on the same line with no spaces.
EDIT2: Maybe this will help. What I'm doing is using PowerShell to write SQL commands, send it to our SQL Server, return the data and use PSWriteHTML to build the report which works fantastic. But I am wanting the first column, which is the ticket number (eg. INC1234) to be a link to the ticket it reads.
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$ReportName
)
## Build the query box
function Read-MultiLineInputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
## Create the Label.
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Size(10,10)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.AutoSize = $true
$label.Text = $Message
## Create the TextBox used to capture the user's text.
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Size(10,40)
$textBox.Size = New-Object System.Drawing.Size(575,200)
$textBox.AcceptsReturn = $true
$textBox.AcceptsTab = $false
$textBox.Multiline = $true
$textBox.ScrollBars = 'Both'
$textBox.Text = $DefaultText
## Create the OK button.
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Size(415,250)
$okButton.Size = New-Object System.Drawing.Size(75,25)
$okButton.Text = "OK"
$okButton.Add_Click({ $form.Tag = $textBox.Text; $form.Close() })
## Create the Cancel button.
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Size(510,250)
$cancelButton.Size = New-Object System.Drawing.Size(75,25)
$cancelButton.Text = "Cancel"
$cancelButton.Add_Click({ $form.Tag = $null; $form.Close() })
## Create the form.
$form = New-Object System.Windows.Forms.Form
$form.Text = $WindowTitle
$form.Size = New-Object System.Drawing.Size(610,320)
$form.FormBorderStyle = 'FixedSingle'
$form.StartPosition = "CenterScreen"
$form.AutoSizeMode = 'GrowAndShrink'
$form.Topmost = $True
$form.AcceptButton = $okButton
$form.CancelButton = $cancelButton
$form.ShowInTaskbar = $true
## Add all of the controls to the form.
$form.Controls.Add($label)
$form.Controls.Add($textBox)
$form.Controls.Add($okButton)
$form.Controls.Add($cancelButton)
## Initialize and show the form.
$form.Add_Shown({$form.Activate()})
$form.ShowDialog() > $null # Trash the text of the button that was clicked.
## Return the text that the user entered.
return $form.Tag
}
## Prompt the SQL Query Box
$Query = Read-MultiLineInputBoxDialog -Message "Enter SQL Query Here" -WindowTitle "SQL Query" -DefaultText "SELECT FROM"
if ($Query -eq $null) { Break }
else { Write-Host "You entered the following text: $Query" }
## Pass query to SQL Server
$Pass = Invoke-Sqlcmd -Query $Query -ServerInstance "MY-SERVER-INSTANCE" -Username "USERNAME" -Password "PASSWORD"
## Output the report and save to the network under the specified name
New-HTML {
New-HTMLTable -EnableColumnReorder -DisableInfo -DataTable $Pass -ExcludeProperty "RowError", "RowState", "Table", `
"ItemArray", "HasErrors" -HideFooter -PagingLength 25 -SearchBuilder
New-HTMLTableStyle -FontFamily Calibri -FontSize 15 -FontStyle normal -TextAlign center -TextColor "#0a0a0a"
New-HTMLTableStyle -FontFamily Calibri -BackgroundColor "#fffdb5" -FontSize 15px -TextColor "#0a0a0a" -TextAlign center -Type RowHover
} -ShowHTML -FilePath "\\Server\$ReportName.html" -Online
The report looks something like:
Ticket: Description:
----------------------------
INC1234 Broken Monitor
INC1235 No Sound
The HTML that PSWriteHTML builds throws all of the ticket numbers on one line so I would like to edit that HTML with the <a href=""> tag to dynamically create links for each ticket # mainly because I don't know how to do it in PS and can't seem to find a good answer through Google - which is why I came here.
Although not familiar with PsWriteHtml, I guess you could simply change the Ticket properties in the array you receive in $Pass:
## Pass query to SQL Server
$Pass = Invoke-Sqlcmd -Query $Query -ServerInstance "MY-SERVER-INSTANCE" -Username "USERNAME" -Password "PASSWORD"
# convert all Tickets into hyperlinks
foreach ($item in $Pass) {
$item.Ticket = '<a href="https://www.website.com/={0}>{0}</a>'-f $item.Ticket
}
Then the rest of your code
## Output the report and save to the network under the specified name
New-HTML {...}

PoweShell script to click HTML button and fill-up form

I'm new to PowerShell and I'm trying to use the following script to login to a page and fill up a form.
$username = "user";
$password = "12345";
$loginUrl = "https://demobrasil5.educamos.com/";
$iterator = 1;
#initialize browser
$ie = New-Object -com internetexplorer.application;
$ie.visible = $true;
$ie.navigate($loginUrl);
while ($ie.Busy -eq $true) { Start-Sleep -Seconds 1; } #wait for browser idle
#login
($ie.document.getElementById("NombreUsuario") |select -first 1).value = $username;
($ie.document.getElementById("Clave") |select -first 1).value = $password;
($ie.document.getElementsByClassName("btn-acceder") |select -first 1).click();
while ($ie.Busy -eq $true) { Start-Sleep -Seconds 1; } #wait for browser idle
#navigate to page and click Create
$ie.navigate("https://demobrasil5.educamos.com/DatosCentro/Usuarios");
while ($ie.Busy -eq $true) { Start-Sleep -Seconds 1; } #wait for browser idle
($ie.document.getElementById("btncrearalumno") |select -first 1).click();
But for the life of me, I can't seem to make this work. This is the HMTL of the page:
<div class="iconos" id="btncrearalumno"><a data-btnbehaviour="link" data-btnmultiple="true" data-btnrequerido="false" data-resizable="False" href="/DatosCentro/Alumnos/CrearAlumno?calendarioescolarId=29d0c494-fb65-4654-8ed2-27461f346e0c&TabActual=0"><span class="glyphBoton_anadir glyphBotones"></span><p>Criar</p></a></div>
I would deeply appreciate any kind of help with this.

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()

How can you get Powershell to interact with elements on a webpage

I am trying to write a Powershell script that will interact with elements of a webpage. To learn the concepts for the script, I am using Armorgames.com as the target url with my aim to use powershell to log into the site, then make a search of available games according to specified search terms, then export the results to a CSV. The attached code sample is what I currently have. But I'm having trouble understanding which parts of the webpage elements I'm searching for and how to input values into the available fields.
I am also getting the error "Method invocation failed because [mshtml.HTMLDocumentClass] does not contain a method named 'getElementsById'" and I don't understand why
$ie = New-Object -ComObject "InternetExplorer.Application"
$requestUrl = "https://armorgames.com/"
$userId = "username-input";
$passwordId = "password-input"
$signIn = "act"
$ie.visible = $true
#ie.silent = $true
$ie.navigate($requestUrl)
while ($ie.busy) {
Start-Sleep -Milliseconds 100
}
$doc = $ie.Document
$doc.getElementsById("input") | % {
if ($_.id -ne $null){
if ($_.id.Contains($signIn)) { $btn = $_ }
if ($_.id.Contains($passwordId)) { $pwd = $_ }
if ($_.id.Contains($userId)) { $user = $_ }
}
}
$user.value = "ExampleUser"
$pwd.value = "MyPassord"
$btn.disabled = $false
$btn.click()
Write-Output $ie
Write-Output "doc is $doc"

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/