Add Optional PSUseConstrainedLanguageMode rule by joshcorr · Pull Request #2165 · PowerShell/PSScriptAnalyzer
PR Summary
This PR adds a new rule PSUseConstrainedLanguageMode that identifies PowerShell patterns incompatible with Constrained Language Mode, helping developers ensure scripts work in restricted environments. This rule is a Warning, but is optional and not enabled by default.
New files:
Rules/UseConstrainedLanguageMode.cs - Implements 14 CLM restriction checks
Tests/Rules/UseConstrainedLanguageMode.tests.ps1 - Adds 46 comprehensive tests
docs/Rules/UseConstrainedLanguageMode.md - Provides complete user documentation
Modified files;
Rules/strings.resx - Adds 16 new diagnostic message strings
Features
Detects CLM Violations:
- Add-Type usage (code compilation)
- Disallowed COM objects (only allows Scripting.Dictionary, Scripting.FileSystemObject, VBScript.RegExp)
- Disallowed .NET types (validates ~70 allowed types including primitives, collections, PowerShell types)
- PowerShell classes (class keyword)
- XAML/WPF usage
- Invoke-Expression usage
- Dot-sourcing patterns
- Type constraints, expressions, and casts
- Member invocations on disallowed types
- Module manifest wildcards and .ps1 references
Signature Awareness:
- Detects signature blocks (# SIG # Begin signature block)
- Applies selective checking to signed scripts (dot-sourcing, parameter types, manifests only)
- Applies full checking to unsigned scripts
Array Type Support:
- Handles array notation correctly ([string[]], [int[][]])
- Strips brackets and validates base types
Configuration:
- IgnoreSignatures property (default: false) bypasses signature detection and enforces full CLM compliance for all scripts
PR Checklist
- PR has a meaningful title
- Use the present tense and imperative mood when describing your changes
- Summarized changes
- Change is not breaking
- Make sure all
.cs,.ps1and.psm1files have the correct copyright header - Make sure you've added a new test if existing tests do not effectively test the code changed and/or updated documentation
- This PR is ready to merge and is not Work in Progress.
- If the PR is work in progress, please add the prefix
WIP:to the beginning of the title and remove the prefix when the PR is ready.
- If the PR is work in progress, please add the prefix
