◐ Shell
clean mode source ↗

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

Testing:
image

PR Checklist