Set StrictMode - PowerShell


Overview

Set-StrictMode elevates the PowerShell execution context to “StrictMode,” enabling stricter error handling and enhancing code reliability. It helps prevent common errors, improves code quality, and ensures consistency in script behavior.

Syntax

Set-StrictMode [[-Mode] {Strict | Warn} ]

Options/Flags

  • -Mode: Specifies the strict mode level. Accepts either “Strict” (default) or “Warn.”
    • Strict: Terminates the script with a non-zero exit code when any error occurs.
    • Warn: Generates warnings but does not terminate the script for errors.

Examples

Basic Usage:

Set-StrictMode -Mode Strict

This sets the strict mode level to “Strict.” Any errors in the script will now terminate execution and return a non-zero exit code.

Customizing Error Handling:

try {
    # Code that may generate errors
} catch {
    Write-Error -Exception $_
}

In this example, the script sets the strict mode level to “Warn” to generate warnings for errors without terminating execution.

Common Issues

  • Performance Impact: Strict mode can have a slight performance impact on large scripts.
  • Over-Strictness: Strict mode can sometimes report errors that may not be critical, leading to false positives.
  • Compatibility with Existing Scripts: Scripts written before PowerShell 3.0 may not be compatible with strict mode and may require modifications.

Integration

  • Combine with Exception Handling: Use try-catch blocks to handle specific errors while allowing others to trigger strict mode behavior.
  • Use with PowerShell Workflow Activities: Set strict mode within a workflow activity using the StrictMode property to ensure consistent error handling across activities.
  • Get-StrictMode: Retrieves the current strict mode level.
  • Enable-StrictMode: Enables strict mode for the current session.
  • Disable-StrictMode: Disables strict mode for the current session.