Using IE COM object within a PS function drops $nulls onto pipeline

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 1 year, 6 months ago.

  • Author
    Posts
  • #32047
    Profile photo of Nate Sternberg
    Nate Sternberg
    Participant

    I found this surprising: each time I call a method of the InternetExplorer.Application COM object within a PS function, it appears to drop a $null (I think?) onto the pipeline, which gets returned along with my intended output. For example...

    function Stuff1{
        "yo momma"
    }
    
    function Stuff2{
        $ie = new-object -ComObject "InternetExplorer.Application"
        $ie.Navigate('http://google.com')
        $ie.Quit() 
        "yo momma"
    }
    
    $a = Stuff1
    "Value of a is '$a' (length: $($a.Length))"
    $b = Stuff2
    "Value of b is '$b' (length: $($b.Length))"
    

    This returns:

    Value of a is 'yo momma' (length: 8)
    Value of b is '  yo momma' (length: 3)
    

    In the second case, I get back an array of 3 elements, the last of which is the string; the first two appear to be null.

    I can suppress this by piping the methods to Out-Null. But was wondering what causes this. It's especially curious because although .Quit() returns void (which I could understand being translated into a null), .Navigate() returns a long.

  • #32048
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That's a common gotcha in PowerShell code. There are several ways to suppress unwanted output, preventing it from going down the pipeline:

    [void]($ie.Navigate('http://google.com'))
    $null = $ie.Navigate('http://google.com')
    $ie.Navigate('http://google.com') | Out-Null
    

    The first two options have roughly equal performance, though I tend to prefer the "$null = " approach. Piping to Out-Null is more visually pleasing, but much much slower. If your code will be called often, or from inside a loop, then you'll probably want to use one of the other options.

    When in doubt, just use these techniques on every command that you don't intend to produce pipeline output. If the command wouldn't have generated any output anyway, there's still no harm done.

  • #32049
    Profile photo of Nate Sternberg
    Nate Sternberg
    Participant

    Thanks Dave! Do you happen to know why this happens? Should I expect any COM object method call to produce this behavior?

  • #32050
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Not sure. A method which returns type void shouldn't be polluting your pipeline, but COM objects are definitely some of the flakiest things you'll work with from a PowerShell script.

You must be logged in to reply to this topic.