PowerShell - 如何以编程方式确定是否设置了 StrictMode?

wfr*_*wfr 8 powershell strict

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

The*_*heo 7

也许一个小功能可以提供帮助:

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
Run Code Online (Sandbox Code Playgroud)

  • 我们还值得一提的是,严格模式设置不会传播到模块范围中。如果建议的 Get-StrictMode 函数包含在模块中,它将报告模块范围内的设置,默认情况下相当于 Set-StrictMode -Off。 (4认同)