Set-StrictMode affecting try/catch inside module.

Welcome Forums General PowerShell Q&A Set-StrictMode affecting try/catch inside module.

This topic contains 2 replies, has 2 voices, and was last updated by

1 year, 3 months ago.

  • Author
  • #84233

    Points: 1
    Rank: Member

    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'
  • #84253

    Points: 0
    Rank: Member

    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
    WARNING: Off
    PS> Set-StrictMode -Version 1
    PS> Get-test
    ERROR: The variable '$nil' cannot be retrieved because it has not been set.
    WARNING: 1

    I'm running PowerShell 5.1 on Windows 10

    • #84265

      Points: 1
      Rank: Member

      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.

The topic ‘Set-StrictMode affecting try/catch inside module.’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort