Author Posts

November 14, 2017 at 12:13 pm

PowerShell v5. Windows 7 Pro.
When I run this function from the console it gives the expected results. As it does
when placed inside a module. However, if I remove the Set-StrictMode -Version 1 line
the module version fails to catch any error and always gives the result 'Off' regardless of the
local StrictMode setting, be it either 1 or 2. I am missing something very simple here
but what?

function Get-test {
   $errorActionPreference = 'Stop'
   #Set-StrictMode -Version 2    # Correctly prints 2
   Set-StrictMode -Version 1     # Correctly prints 1
   $version = '0'
   try {
      $value = '2'
      $z = "2 * $nil"       
      $value = '1'
      $z = 2 * $nil         
      $value = 'Off'
   catch {
      "ERROR: $_"
   Write-Warning $value
   $errorActionPreference = 'Continue'

November 14, 2017 at 8:27 pm

If you run the code within your try\catch with strict mode off you'll see that everything works so you never get an error thrown and reach $value = 'Off'

PS> $value = '2'
PS> $z = "2 * $nil"
PS> $z
2 *
PS> $value = '1'
PS> $z = 2 * $nil
PS> $z
PS> $value = 'Off'
PS> $value

if Set-StrictMode is Off then you're running without any of the tests

when I run the function with Set-Strictmode set OUTSIDE the function it works as expected

PS> Get-test

PS> Set-StrictMode -Version 1

PS> Get-test
ERROR: The variable '$nil' cannot be retrieved because it has not been set.

I'm running PowerShell 5.1 on Windows 10

November 15, 2017 at 12:25 am

This is what normally happens in the script; but load the above code into a module (omitting any Set-StrictMode lines), then Import-Module c:\modules\testModule, locally Set-StrictMode -Version 2, run Get-Test. Always returns 'Off', as the catch block is bypassed. I would like to know why; and how to import the StrictMode value into the module scope.