无法使用IHTMLDocument2

问题描述 投票:3回答:3
$wc = New-Object System.Net.WebClient
$DownloadString = $wc.DownloadString("http://www.example.com")
$HTML = New-Object -ComObject "HTMLFile"
$HTML.IHTMLDocument2_write($DownloadString)

运行服务器脚本

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

开发PC

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

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

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

后来......

Unable to find type [mshtml.HTMLDocumentClass].
powershell internet-explorer windows-server powershell-v5.0 ihtmldocument2
3个回答
7
投票

我和我的朋友正试图解决这个问题。我们在他的机器上一直遇到这个错误,而我的同一个脚本工作,(两者都是相同的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

我们发现在他的计算机上,$ 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)
}

2
投票

有帮助的问题:Can't use InternetExplorer.Application object?

从我的机器复制了Microsoft.mshtml.dll,该机器在C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies中运行到服务器。然后在我的脚本开头添加了Add-Type -Path "C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies\microsoft.mshtml.dll"

我还注意到一些IE安全框出现(运行我的脚本时),Windows服务器的IE安全设置可能会干扰(因为它远远高于客户端)。也许如果我的设置降低了,这将在不复制.dll的情况下解决。但是,我认为升级到PSv5至关重要(因为即使enum也未被识别)。


0
投票

我不知道为什么,但在电脑上安装了微软办公室后,一切正常。试过两台不同的电脑。

© www.soinside.com 2019 - 2024. All rights reserved.