powershell - 无法使用 IHTMLDocument2

标签 powershell internet-explorer windows-server powershell-5.0 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

开发电脑
Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      15063  502

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

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



后来下线...
Unable to find type [mshtml.HTMLDocumentClass].

最佳答案

我和我的 friend 试图确定这个问题。当相同的脚本在我的机器上运行时,我们一直在他的机器上收到此错误(两者都使用相同的 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)
}

关于powershell - 无法使用 IHTMLDocument2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46307976/

相关文章:

powershell - 如何使用 DSC 在 Azure VM 上安装存储在 Azure 文件共享中的 exe 文件?

powershell - () 和 $() 的区别

java - Selenium IEServerDriver 找不到 IE9 的新窗口

html - IE9 中表格背景颜色的奇怪问题

linux - 连接到 UCS/Samba 服务器的 Windows 客户端 - 加入操作不成功

events - PowerShell:如何在远程服务器上运行脚本?

powershell - 有人有这个 Powershell "Update-Help"命令吗?

css - 如何改进 IE 11 中的字体

php - NTLM 身份验证 - 在 PHP 中获取 Windows 登录名、域和主机

ms-access - 我可以将 MS Access 应用程序链接到 Linux 服务器上的 Postgresql 吗?我可以/应该使用 ODBC 吗?