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?
Asked
Active
Viewed 1,212 times
7
-
2I don't think there's any supported way to get it from the public API, reflection is the only way – Mathias R. Jessen Jul 25 '20 at 15:16
-
Rohn Edwards ( https://gallery.technet.microsoft.com/scriptcenter/Get-StrictMode-Get-the-900af6da ) 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. – wfr Jul 26 '20 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 Hope May 01 '22 at 01:01
-
Rohn Edwards addressed the StrictMode issue here: https://rohnspowershellblog.wordpress.com/2013/12/18/get-strictmode/ . As of today, the links on his blog do not take you to the code. – wfr May 18 '22 at 08:58
1 Answers
7
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

Theo
- 57,719
- 8
- 24
- 41
-
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”. – wfr Jul 26 '20 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. – Theo Jul 26 '20 at 15:15
-
4It 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. – wfr Jul 27 '20 at 13:28
-
@wfr is there no way around this? This would be a very useful function to include in my module – Brett Aug 11 '23 at 18:34
-
@Brett having read your comment I gave it some more thought but could not find a work-around. – wfr Sep 01 '23 at 14:17