recursive function not working correct?

1

I've created a function "Query-ComDomElements.ps1" to query HTML objects.

This works quite well when querying only one object and querying that again.

When I try calling it in recursion it however fails and I don't understand why. The code/objects is/are the very same.

Could anyone please enlighten me why the query .container>img is not working, but querying .container and with that img is?

The error I get when querying both (and thus calling the function recursively) is:

Exception calling "InvokeMember" with "5" argument(s): "Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))"
At C:\path\to\Query-ComDomElements.ps1:31 char:5
+ ...             $result = [System.__ComObject].InvokeMember("getElementsB ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : COMException

Here my sample script (function Query-ComDomElements.ps1 not included but on github):

. C:\path\to\Query-ComDomElements.ps1

$ie = New-Object -ComObject "InternetExplorer.Application"

$ie.Navigate2("https://www.gpunktschmitz.de/")

while($ie.Busy) {
    Start-Sleep -Seconds 1
}


#this works
$imgContainer = Query-ComDomElements -Query '.container' -Dom $ie.Document
$image = Query-ComDomElements -Query 'img' -Dom $imgContainer -Property 'src'

#this fails
$image = Query-ComDomElements -Query '.container>img' -Dom $ie.Document -Property 'src'

$ie.quit()
html
powershell
internet-explorer
dom
recursion
asked on Stack Overflow Jan 8, 2018 by Guenther Schmitz • edited Jan 8, 2018 by Guenther Schmitz

1 Answer

2

I think the problem is occurring because $dom ends up being an array with two elements when it is passed in on the second iteration. One (dirty) fix for this would be to use Select-Object to just get the first element (suggest using Select rather than [0] so that if its not an array it doesn't error):

if($SecondQuery -eq $false) {
    if($Property -ne $false -and $Property -ne '*') {
        return $result.$Property
    } else {
        return $result
    }
} else {
    return Query-ComDomElements -Query $SecondQuery -Dom ($result | select -first 1) -Property $Property
}
answered on Stack Overflow Jan 8, 2018 by Mark Wragg • edited Jan 8, 2018 by Matt

User contributions licensed under CC BY-SA 3.0