Search code examples
powershellie-automation

PowerShell: Testing whether an element exists in web page


I am trying to find whether an element exists in a web page:

$ie = New-Object -com InternetExplorer.Application
$ie.visible = $true
$ie.Navigate("http://10.0.0.1")
BrowserReady($ie) # wait for page to finish loading
if ($ie.Document.getElementById("admin")) {
  $ie.Document.getElementById("admin").value = "adminuser"
}
etc, etc

(Yes, it is possible for the page at http://10.0.0.1 to NOT contain the element with id "admin" - the why doesn't matter.)

My problem is that the test in line 5 doesn't seem to work correctly: it always returns TRUE whether the element exists or not. I have also tried

if ($ie.Document.getElementById("admin") -ne $NULL) {...}

with same results.

I am working on a Windows 10 system. Any ideas?


Solution

  • The problem is in your comparison. The command Document.getElementById is returning with DBNull which by itself doesn't equals to Null. Therefore, when you execute:

    if ($ie.Document.getElementById("admin"))
    {
       ...
    }
    

    You'd always returned with True. As you can see in the following example, $my_element isn't equals to $null and its type is DBNull.

    PS > $my_element = $ie.Document.getElementById("admin")
    
    PS > $my_element -eq $null
    False
    
    PS > $my_element.GetType()
    
    IsPublic IsSerial Name                                     BaseType                                                                                                     
    -------- -------- ----                                     --------   
    True     True     DBNull                                   System.Object   
    

    I'd suggest you to use one of this comparisons to determine if "admin" really exists:

    PS > $my_element.ToString() -eq ""
    True
    
    PS > [String]::IsNullOrEmpty($my_element.ToString())
    True
    
    PS > $my_element.ToString() -eq [String]::Empty
    True
    

    If the comparisons return with True it means that the value is Empty so "admin" is not exists. Of course you can use -ne for more convenience.