1

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?

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Ravikanth, thanks - your fix worked. But why didn't it work when I used $doc.getElementsByName("q")? Is there anything wrong with using that?
Not sure. It has several properties. May need to look at it once again.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.