$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/