I know that I can override in a script or function the StrictMode setting inherited from a higher scope. But how can I find out in a script or function what the inherited setting is?
4
-
2I don't think there's any supported way to get it from the public API, reflection is the only way– Mathias R. JessenJul 25, 2020 at 15:16
-
Rohn Edwards ( gallery.technet.microsoft.com/scriptcenter/… ) provided an elaborate solution using reflection that is specific to Windows PowerShell. It does not work in PowerShell Core. I definitely would prefer getting the setting from PowerShell’s public API instead of a non-public field.– wfrJul 26, 2020 at 14:52
-
@wfr Rohn Edwards link is broken... can you update the link and/or also include the name of the code solution.– George 2.0 HopeMay 1 at 1:01
-
Rohn Edwards addressed the StrictMode issue here: rohnspowershellblog.wordpress.com/2013/12/18/get-strictmode . As of today, the links on his blog do not take you to the code.– wfrMay 18 at 8:58
Add a comment
|
1 Answer
Perhaps a small function can help:
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
-
Your suggestion to determine the current StrictMode setting by forcing terminating errors in try/catch blocks in sequence from most restrictive to least restrictive largely answers the question. There is just one caveat, it cannot distinguish between strict mode version “3.0” and “latest”.– wfrJul 26, 2020 at 15:09
-
1@wfr Yes, there is indeed no way to test for
Latest
. AFAIK currently this is the same as version 3. However, maybe in the future, there will be another versioned strictmode. In that case we need to update the function.– TheoJul 26, 2020 at 15:15 -
3It might also we worth to mention, that strict mode settings are not propagated into module scopes. Were the proposed Get-StrictMode function included in a module, it would report the setting in the module scope, which by default is equivalent to Set-StrictMode -Off.– wfrJul 27, 2020 at 13:28