Skip to content

Bind StrictMode to a specific function #20432

Open

Description

@iRon7

Summary of the new feature / enhancement

Currently the Set-StrictMode might be set from two possible scopes:

  1. From outside a function/cmdlet:
Set-StrictMode -Version Latest
function MyFunction {
  Write-Host '...'
}

But this might undesirably affect other functions, see: #18740 (and possibly even VSCode extensions)
Besides as Set-StrictMode isn't strictly linked to a function, it might get disconnected from specific tests when e.g. dot sourced:

Set-StrictMode -Version Latest
. .\MyScript.ps1
  1. From within a specific process block of a function (as suggested here by @MartinGC94)
function MyFunction {
  param(
    $FormatAccentColor = $Host.PrivateData.FormatAccentColor
  )
  process {
    Set-StrictMode -Version Latest
    Write-Host '...'
  }
}

Aside from the fact that you will need to do this from every process block, you (afaik) can't cover the param block.

Proposed technical implementation details (optional)

As once suggested in #16388:

Control StrictMode from a System.Diagnostics.CodeAnalysis Namespace class cmdlet annotation.
Wishful thinking:

[Diagnostics.CodeAnalysis.StrictMode(version=6)]
function MyStrictFunction {
  param(
    $FormatAccentColor = $Host.PrivateData.FormatAccentColor
  )
  process {
    Write-Host '...'
  }
}

function ALooselyFunction { # (in the same scope of MyStrictFunction)
  Write-Host $SomethingThatIsNotSet
}

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Oct 4, 2023
  2. iRon7 commented on Oct 5, 2023

    @iRon7
    Author

    Or probably better, using [CmdletBinding()], something like (wishful thinking):

    function MyStrictFunction {
      [CmdletBinding(StrictModeVersion=6)]
      param(
        $FormatAccentColor = $Host.PrivateData.FormatAccentColor
      )
      process {
        Write-Host '...'
      }
    }
    
  3. changed the title [-]Control `StrictMode` from the `System.Diagnostics.CodeAnalysis Namespace`[/-] [+]Bind `StrictMode` to a specific function[/+] on Oct 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementNeeds-Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions