如何在 PowerShell 中禁用 Internet Explorer 解析

Jay*_*uzi 3 powershell

Invoke-WebRequest如果 Internet Explorer 不可用,cmdlet 可能会失败* :

The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
Run Code Online (Sandbox Code Playgroud)

如果我使用的计算机具有正常运行的 Internet Explorer,-UseBasicParsing则不需要。我想测试我的脚本是否可以在未运行 IE 或已卸载 IE 的计算机上运行。在我的测试环境中,如何刻意创造发生上述错误的条件呢?

* PowerShell 6.0.0 之前。

mkl*_*nt0 6

如果我使用的计算机具有正常运行的 Internet Explorer,-UseBasicParsing则不需要。

即使不需要避免错误,您也应该使用此开关,除非确实需要将响应解析为可通过属性访问的 DOM。 防止这种不必要的解析产生的开销。.ParsedHTML-UseBasicParsing

因此,如果您不需要 Internet Explorer 介导的 DOM 解析,则始终使用
-UseBasicParsing就可以,甚至可以在跨版本场景
中使用:
虽然在PowerShell (Core)-UseBasicParsing (v6+) 中从不需要- 其中解析为 DOM 不是'甚至不可- 您仍然可以在那里使用它,而不会产生不良影响。


如果您想避免将开关传递-UseBasicParsing每个调用,您可以通过首选项变量预设 -UseBasicParsing 会话范围$PSDefaultParameterValues

# Note: '*' targets *all* commands that have a -UseBasicParsing parameter
#       While you could 'Invoke-WebRequest' instead of '*',
#       '*' ensures that 'Invoke-RestMethod' is covered too.
$PSDefaultParameterValues['*:UseBasicParsing'] = $true
Run Code Online (Sandbox Code Playgroud)

如果您想将此预设范围限制为给定脚本(以及从中调用的脚本/函数),请使用此答案中显示的技术。


如何刻意创造发生上述错误的条件呢?

如果您想对模拟错误条件的代码运行测试,以确保所有代码都使用-UseBasicParsing

  • 安装Pester模块,例如使用Install-Module -Scope CurrentUser Pester. Pester 是广泛使用的 PowerShell 测试框架。

  • 使用 Pester 的模拟功能来模拟错误,Invoke-WebRequest只要Invoke-RestMethod没有. -UseBasicParsing

这是一个简单的示例(保存到,EnforceBasicParsing.Tests.ps1然后使用 调用.\EnforceBasicParsing.Tests.ps1):

Describe 'Enforce -UseBasicParsing' {
  BeforeAll {
    # Set up mocks for Invoke-WebRequest and Invoke-RestMethod
    # that throw whenever -UseBasicParsing isn't passed.
    $exceptionMessageAndErrorId = "Missing -UseBasicParsing"
    'Invoke-WebRequest', 'Invoke-RestMethod' | ForEach-Object {
      Mock -CommandName $_  `
           -ParameterFilter { -not $UseBasicParsing } `
           -MockWith{ throw $exceptionMessageAndErrorId } 
    }
  }
  It 'Fails if -UseBasicParsing is NOT used with Invoke-WebRequest' {
    { Invoke-WebRequest http://example.org } |
      Should -Throw -ErrorId $exceptionMessageAndErrorId
  }
  It 'Fails if -UseBasicParsing is NOT used with Invoke-RestMethod' {
    { Invoke-RestMethod http://example.org } |
      Should -Throw -ErrorId $exceptionMessageAndErrorId
  }
  It 'Deliberately failing test' {
    { Invoke-RestMethod http://example.org } |
      Should -Not -Throw -ErrorId $exceptionMessageAndErrorId
  }
}
Run Code Online (Sandbox Code Playgroud)

前两个测试成功,而第三个测试是故意失败的,这表明如果测试针对不使用-UseBasicParsing.

另请参阅:Pester 文档