【问题标题】:InternetExplorer COM document available in PowerShell ISE but not in regular PS consoleInternetExplorer COM 文档在 PowerShell ISE 中可用,但在常规 PS 控制台中不可用
【发布时间】:2014-11-22 04:27:30
【问题描述】:

以下代码在 PowerShell ISE 中运行,但在常规 PowerShell 控制台中运行时,文档对象为空:

$ie = New-Object -COM InternetExplorer.Application
$ie.Navigate('http://www.example.com')
$ie.Visible = $true
do { Start-Sleep -m 100 } while ( $ie.busy )

$document = $ie.document
$window = $document.parentWindow

"Ready state: " + $ie.ReadyState
"Document: " + $document
"Window: " + $window

PowerShell ISE 中的输出:

Ready state: 4
Document: mshtml.HTMLDocumentClass
Window: System.__ComObject

常规 PowerShell 控制台中的输出:

Ready state: 4
Document: mshtml.HTMLDocumentClass
Window:

在 PowerShell.exe 中运行时,$window$document 的所有其他属性为空。为什么会这样以及如何解决?谢谢!

【问题讨论】:

    标签: internet-explorer powershell com scripting


    【解决方案1】:

    尝试使用-sta 选项执行您的常规控制台。

    【讨论】:

    • PowerShell 的 MTA\STA 默认值似乎在 PowerShell v2.0 和 v3.0 之间发生了变化。
    • 我很难相信这是原因,因为InternetExplorer.Application 是一个进程外 COM 对象。
    【解决方案2】:

    您应该检查ReadyState 属性是否完成,而不是检查不稳定的Busy 属性,它可能会振荡并且主要用于判断停止按钮是否应该可用:

    do { Start-Sleep -m 100 } while ( $ie.ReadyState -ne 4 )
    

    【讨论】:

    • 我也试过了,但没有解决这个特殊问题。使用 -STA 开关运行 PowerShell 似乎可以正常工作。
    • 关于使用 ReadyState 的好建议顺便说一句,我找到了更多关于 here 的信息。
    猜你喜欢
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2018-09-08
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多