【问题标题】:PowerShell - how to determine programmatically whether StrictMode is set?PowerShell - 如何以编程方式确定是否设置了 StrictMode?
【发布时间】:2020-07-25 15:03:07
【问题描述】:

我知道我可以在脚本或函数中覆盖从更高范围继承的 StrictMode 设置。但是如何在脚本或函数中找出继承的设置是什么?

【问题讨论】:

  • 我认为没有任何受支持的方法可以从公共 API 中获取它,反射是唯一的方法
  • Rohn Edwards (gallery.technet.microsoft.com/scriptcenter/…) 使用特定于 Windows PowerShell 的反射提供了一个精心设计的解决方案。它在 PowerShell Core 中不起作用。我肯定更喜欢从 PowerShell 的公共 API 而不是非公共字段中获取设置。

标签: powershell strict


【解决方案1】:

也许一个小函数可以提供帮助:

function Get-StrictMode {
    # returns the currently set StrictMode version 1, 2, 3
    # or 0 if StrictMode is off.
    try { $xyz = @(1); $null = ($null -eq $xyz[2])}
    catch { return 3 }

    try { "Not-a-Date".Year }
    catch { return 2 }

    try { $null = ($undefined -gt 1) }
    catch { return 1 }

    return 0
}

Get-StrictMode

【讨论】:

  • 您建议通过强制在 try/catch 块中按从最严格到最不严格的顺序终止错误来确定当前的 StrictMode 设置,这在很大程度上回答了这个问题。只有一个警告,它无法区分严格模式版本“3.0”和“最新”。
  • @wfr 是的,确实没有办法测试Latest。 AFAIK 目前这与版本 3 相同。但是,也许将来会有另一个版本的严格模式。在这种情况下,我们需要更新函数。
  • 值得一提的是,严格模式设置不会传播到模块范围内。如果建议的 Get-StrictMode 函数包含在模块中,它将报告模块范围内的设置,默认情况下等效于 Set-StrictMode -Off。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
相关资源
最近更新 更多