powershellinternet-explorerwindows-serverpowershell-5.0ihtmldocument2

Unable to use IHTMLDocument2


$wc = New-Object System.Net.WebClient
$DownloadString = $wc.DownloadString("http://www.example.com")
$HTML = New-Object -ComObject "HTMLFile"
$HTML.IHTMLDocument2_write($DownloadString)

Server script runs on

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14409  1005

Development PC

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      15063  502

My Windows 10 development PC worked fine with the code above. I want to run this on my Server 2008 R2 x64 machine. I upgraded it to PowerShell v5. I get the following:

Method invocation failed because [System.__ComObject] does not contain a method named 'IHTMLDocument2_write'.

And later down the line...

Unable to find type [mshtml.HTMLDocumentClass].

Solution

  • My friend and I were trying to nail down this issue. We kept getting this error on his machine while the same script worked on mine, (same Windows 10 build version on both).

    Method invocation failed because [System.__ComObject] does not contain a method named 'IHTMLDocument2_write'.
    At <script_path\script_name>:184 char:1
    + $HTML.IHTMLDocument2_write($content)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (IHTMLDocument2_write:String) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    

    We found that on his computer the $html object had ie9 properties and on mine it had IHTML properties. He identified that my computer had MS Office installed, but his did not. He tried the code on another of his computers running Server 2008 that did have Office (even an old version like 2010) installed and our script worked fine.

    Proposed solution:

    $HTML = New-Object -Com "HTMLFile"
    
    try {
        # This works in PowerShell with Office installed
        $html.IHTMLDocument2_write($content)
    }
    catch {
        # This works when Office is not installed    
        $src = [System.Text.Encoding]::Unicode.GetBytes($content)
        $html.write($src)
    }