无法使用IHTMLDocument2

Tyl*_*ney 4 powershell internet-explorer ihtmldocument2 windows-server powershell-5.0

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

运行服务器脚本

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14409  1005
Run Code Online (Sandbox Code Playgroud)

开发PC

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      15063  502
Run Code Online (Sandbox Code Playgroud)

我的Windows 10开发PC在上面的代码中运行良好.我想在我的Server 2008 R2 x64机器上运行它.我将其升级到PowerShell v5.我得到以下内容:

方法调用失败,因为[System .__ ComObject]不包含名为"IHTMLDocument2_write"的方法.

后来......

Unable to find type [mshtml.HTMLDocumentClass].
Run Code Online (Sandbox Code Playgroud)

小智 8

我和我的朋友正试图解决这个问题.我在他的机器上一直遇到这个错误,而我的同一个脚本工作,(两者都是相同的Windows 10构建版本).

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
Run Code Online (Sandbox Code Playgroud)

我们发现在他的计算机上,$ html对象具有ie9属性,并且在我的计算机上它具有IHTML属性.他发现我的电脑安装了MS Office,但他没有.他在另一台运行Server 2008的计算机上尝试了代码,该计算机安装了Office(甚至包括像2010这样的旧版本)并且我们的脚本运行良好.

建议的解决方案:

$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)
}
Run Code Online (Sandbox Code Playgroud)