无法使用ihtmldocument2


$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 Development PC在上面的代码上正常工作。我想在我的服务器2008 R2 X64机器上运行此操作。我将其升级到Powershell V5。我得到以下内容:

方法调用失败了,因为[系统.__ comobject]不包含名为" ihtmldocument2_write"的方法。

及以后的线...

Unable to find type [mshtml.HTMLDocumentClass].

我和我的朋友正在尝试解决这个问题。当同一脚本在我的脚本上使用时,我们一直在他的机器上遇到此错误(同一Windows 10构建版本)。

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

我们在他的计算机上发现$ HTML对象具有IE9属性,在我的计算机上,它具有IHTML属性。他确定我的计算机已经安装了MS Office,但他没有安装。他在运行的另一台计算机服务器2008上尝试了该代码,该计算机确实已安装了办公室(甚至像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)
}

更新:

具有讽刺意味

l0wm3mory的答案现在是正确的答案。

原始:

有帮助的问题:无法使用InternetExpplorer.Application对象?

从我的机器中复制了Microsoft.mshtml.dll,该机器在C:Program Files (x86)Microsoft.NETPrimary Interop Assemblies中使用的服务器。然后在脚本的开头添加Add-Type -Path "C:Program Files (x86)Microsoft.NETPrimary Interop Assembliesmicrosoft.mshtml.dll"

我还注意到某些IE安全框出现(运行脚本时),并且Windows Server的IE安全设置可能会干扰(因为它比客户端要高得多)。也许如果我的设置降低了,则可以在不复制.dll的情况下解决。但是,我认为升级到PSV5至关重要(甚至enum也没有识别)。

我不知道为什么,但是在计算机上安装了Microsoft Office之后,一切对我来说都很好。在两台不同的计算机上尝试。

我有上面的问题,并且能够通过从Internet下载DLL文件并在PowerShell中进行注册来解决它。我在https://www.dllme.com/dll/files/microsoft_mshtml_dll.html上找到了DLL,但不确定是否是正式的。然后,我将其复制到System32文件夹,然后在下面运行两个命令。

Add-Type -Path "C:WindowsSystem32Microsoft.mshtml.dll"
Add-Type -AssemblyName "Microsoft.mshtml"

和语音LA,问题已经消失了。

最新更新