powershellscopestrict

How do I use Set-StrictMode to only set strict mode for the private scope?


My script needs to call third party scripts that do not work under strict mode. Right now I explicitly disable the strict mode in my script for these calls:

Set-StrictMode -Version 3
…my script here…
Set-StrictMode -Off
.\thirdparty.ps1
Set-StrictMode -Version 3
…the rest of my script here…

Given the strict mode is only set for the "current" and "child" scopes, and it is possible to, let say, create private variables not visible to child scopes, is there an option to also set the strict mode as private for the current scope? That would save me some effort trying to track the strict mode settings.


Solution

  • No, strict mode is not a variable that can be locked to your current scope. It would require changing how powershell itself stores and checks for strict mode

    You could create a function that runs Set-StrictMode -Off before thirdparty.ps1, since it will be considered a child scope, and won't change the mode of your overall script that calls it:

    Set-StrictMode -Version 3
    
    function do-badThing {
      Set-StrictMode -Off
      "Not-a-Date".Year
    
      # or call your other script
      ./thirdparty.ps1 
    }
    
    do-badThing  ## succeeds
    
    "Not-a-Date".Year  ## still fails due to strict mode
    

    Otherwise, the best you can do is what you have where you change the mode just before and after calling something that doesn't behave