### Example of Correct Comment-Based Help Source: https://context7.com/powershell/psscriptanalyzer/llms.txt This example shows the correct placement and structure for comment-based help preceding a function definition, as required by the `PSProvideCommentHelp` rule. It includes standard help sections like `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`, and `.OUTPUTS`. ```powershell # Correct pattern: comment-based help before function definition <# .SYNOPSIS Retrieves log data from the specified path. .DESCRIPTION Opens the log file at Path and returns structured log entries. .PARAMETER Path The path to the log file. .EXAMPLE Get-LogData -Path C:\Logs\app.log .OUTPUTS PSCustomObject[] #> function Get-LogData { [CmdletBinding()] Param( [Parameter(Mandatory)] [string]$Path ) # implementation } ``` -------------------------------- ### Install PSScriptAnalyzer from PowerShell Gallery Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md Use this command to install PSScriptAnalyzer from the PowerShell Gallery. Ensure you have PowerShell open in a Terminal. ```powershell Install-Module -Name PSScriptAnalyzer ``` -------------------------------- ### Correct Casing Example Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseCorrectCasing.md Shows the correct casing for a cmdlet, parameter, and operator, adhering to the PSUseCorrectCasing rule. ```powershell foreach ($file in Get-ChildItem -Recurse) { $file.Extension -eq '.txt' } Invoke-Command { 'foo' } -RunAsAdministrator ``` -------------------------------- ### Use Invoke-CimMethod Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWMICmdlet.md This example demonstrates the correct usage of Invoke-CimMethod, which is the recommended replacement for Invoke-WmiMethod. ```powershell Invoke-CimMethod -ClassName Win32_Process -MethodName 'Create' -Arguments @{ CommandLine = 'notepad.exe' } ``` -------------------------------- ### Example: Inline Parameters Correct Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseConsistentParametersKind.md Demonstrates the correct usage of the 'Inline' parameter definition when the rule is configured for this style. ```powershell # Correct function f([Parameter()]$FirstParam) { return } ``` -------------------------------- ### Aligned Hashtable and Enum Example Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AlignAssignmentStatement.md Shows the same hashtable and enum definition as the previous example, but with assignments aligned vertically for better readability. ```powershell $hashtable = @{ property = 'value' anotherProperty = 'another value' } enum Enum { member = 1 anotherMember = 2 } ``` -------------------------------- ### Example: Add-Type Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseConstrainedLanguageMode.md Demonstrates the use of Add-Type, which is not permitted in Constrained Language Mode for unsigned scripts. This example would be flagged by the PSUseConstrainedLanguageMode rule. ```powershell # Example of Add-Type, which is restricted in CLM Add-Type -TypeDefinition @" public class Test { public static void Main() { System.Console.WriteLine("Hello World"); } } "@ [Test]::Main() ``` -------------------------------- ### Security Rule Examples and Fixes Source: https://context7.com/powershell/psscriptanalyzer/llms.txt This section lists several security rules and the anti-patterns they detect. For each rule, it provides an example of flagged code and suggests a corrected approach, focusing on secure practices like using `Read-Host -AsSecureString` instead of plain text passwords and employing `PSCredential` types. ```powershell # Individual security rules and what they catch: # # PSAvoidUsingConvertToSecureStringWithPlainText [Error] # Flags: ConvertTo-SecureString -String $pwd -AsPlainText -Force # Fix: Read-Host -AsSecureString # # PSAvoidUsingPlainTextForPassword [Warning] # Flags: param([string]$Password) # Fix: param([SecureString]$Password) or param([PSCredential]$Credential) # # PSAvoidUsingUsernameAndPasswordParams [Error] # Flags: functions that have both -Username and -Password parameters # Fix: use a single [PSCredential] parameter # # PSAvoidUsingComputerNameHardcoded [Error] # Flags: -ComputerName 'MYSERVER01' # Fix: accept computer name as a parameter # # PSUsePSCredentialType [Warning] # Flags: [string]$Credential (should be [PSCredential]) # # PSAvoidUsingInvokeExpression [Warning] # Flags: Invoke-Expression $userInput ``` -------------------------------- ### Example: ParamBlock Parameters Correct Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseConsistentParametersKind.md Demonstrates the correct usage of the 'ParamBlock' parameter definition when the rule is configured for this style. ```powershell # Correct function g { param([Parameter()]$FirstParam) return } ``` -------------------------------- ### DSC Class Resource Functions (Wrong) Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCStandardDSCFunctionsInResource.md Demonstrates a class-based DSC resource that is missing the Get method. ```powershell [DscResource()] class MyDSCResource { [DscProperty(Key)] [string] $Name [void] Set() { ... } [bool] Test() { ... } } ``` -------------------------------- ### Use Direct Command Execution Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingInvokeExpression.md This snippet shows the correct way to achieve the same result as the 'Wrong' example by directly calling the cmdlet. This is the recommended and secure approach. ```powershell Get-Process ``` -------------------------------- ### Examples of Cmdlet Alias Usage Source: https://context7.com/powershell/psscriptanalyzer/llms.txt These examples illustrate the incorrect usage of PowerShell aliases like `gps` and `%` compared to the correct usage of their full cmdlet names (`Get-Process` and `ForEach-Object`). The `Get-Alias` command is shown for checking alias mappings. ```powershell # Wrong gps | Where-Object { $_.WorkingSet -gt 20MB } % { $_ * 2 } ``` ```powershell # Correct Get-Process | Where-Object { $_.WorkingSet -gt 20MB } ForEach-Object { $_ * 2 } ``` ```powershell # Check which alias maps to which cmdlet Get-Alias gps # -> Get-Process Get-Alias dir # -> Get-ChildItem ``` -------------------------------- ### Use Full Cmdlet Names Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingCmdletAliases.md This is the corrected version of the previous example, using the full cmdlet name 'Get-Process' instead of its alias 'gps'. ```powershell Get-Process | Where-Object {$_.WorkingSet -gt 20000000} ``` -------------------------------- ### Use Get-CimInstance and Remove-CimInstance Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWMICmdlet.md This example demonstrates the correct usage of Get-CimInstance and Remove-CimInstance, which are the recommended replacements for Get-WmiObject and Remove-WmiObject. ```powershell Get-CimInstance -Query 'Select * from Win32_Process where name LIKE "myprocess%"' | Remove-CIMInstance ``` -------------------------------- ### Rebuild Documentation Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md Use this command to rebuild the project's documentation. This is typically done after initial setup or when documentation changes are made. ```powershell ./build.ps1 -Documentation ``` -------------------------------- ### Invoke PowerShell Script Analyzer with Custom Rules Source: https://context7.com/powershell/psscriptanalyzer/llms.txt These examples demonstrate how to invoke `Invoke-ScriptAnalyzer` using custom rules. The first example loads both default and custom rules, while the second runs only the specified custom rules. The third example shows how to list available custom rules. ```powershell # Load the custom rule alongside built-in rules Invoke-ScriptAnalyzer -Path .\Target.ps1 \ -CustomRulePath .\MyCustomRules.psm1 \ -IncludeDefaultRules ``` ```powershell # Run only custom rules (no built-in rules) Invoke-ScriptAnalyzer -Path .\Target.ps1 \ -CustomRulePath .\MyCustomRules.psm1 ``` ```powershell # List the custom rules Get-ScriptAnalyzerRule -CustomRulePath .\MyCustomRules.psm1 ``` -------------------------------- ### Incorrect Casing Example Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseCorrectCasing.md Demonstrates incorrect casing for a cmdlet, parameter, and operator, which would be flagged by the PSUseCorrectCasing rule. ```powershell ForEach ($file in Get-childitem -Recurse) { $file.Extension -EQ '.txt' } invoke-command { 'foo' } -runasadministrator ``` -------------------------------- ### Use Write-Verbose and Write-Output Correctly Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWriteHost.md This example demonstrates the correct usage of Write-Verbose for informational messages and Write-Output for returning objects. The Verbose parameter must be supported for Write-Verbose to display output. ```powershell function Get-MeaningOfLife { [CmdletBinding()]Param() # makes it possible to support Verbose output Write-Verbose 'Computing the answer to the ultimate question of life, the universe and everything' Write-Output 42 } ``` -------------------------------- ### Function With Correct Comment Help Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/ProvideCommentHelp.md This example shows a function correctly implemented with comprehensive comment-based help, adhering to standard PowerShell help sections like .Synopsis, .DESCRIPTION, .EXAMPLE, and others. ```powershell <# .Synopsis Short description .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES General notes .COMPONENT The component this cmdlet belongs to .ROLE The role this cmdlet belongs to .FUNCTIONALITY The functionality that best describes this cmdlet #> function Get-File { [CmdletBinding()] Param ( ... ) } ``` -------------------------------- ### Avoid Invoke-WmiMethod Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWMICmdlet.md This example shows the incorrect usage of Invoke-WmiMethod. Use Invoke-CimMethod instead. ```powershell Invoke-WmiMethod -Class Win32_Process -Name 'Create' -ArgumentList @{ CommandLine = 'notepad.exe' } ``` -------------------------------- ### Correct Use of Named Parameters Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingPositionalParameters.md This example shows the correct way to call a cmdlet using named parameters for improved clarity and maintainability. ```powershell Get-Command -Noun ChildItem -Module Microsoft.PowerShell.Management ``` -------------------------------- ### Avoid Get-WmiObject and Remove-WmiObject Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWMICmdlet.md This example demonstrates the incorrect usage of Get-WmiObject and Remove-WmiObject. Use Get-CimInstance and Remove-CimInstance instead. ```powershell Get-WmiObject -Query 'Select * from Win32_Process where name LIKE "myprocess%"' | Remove-WmiObject ``` -------------------------------- ### Function Without Comment Help Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/ProvideCommentHelp.md This example demonstrates a function that is missing comment-based help, which would trigger a violation of the PSProvideCommentHelp rule. ```powershell function Get-File { [CmdletBinding()] Param ( ... ) } ``` -------------------------------- ### Function Without SupportsShouldProcess Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseShouldProcessForStateChangingFunctions.md This example shows a function that does not include the SupportsShouldProcess argument. Functions that change system state should include this argument to support Confirm and WhatIf parameters. ```powershell function Set-ServiceObject { [CmdletBinding()] param ( [string] $Parameter1 ) ... } ``` -------------------------------- ### Use Write-Host for Display-Only Output with Show Verb Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWriteHost.md This example shows a function with the 'Show' verb, where Write-Host is acceptable for displaying information directly to the user. ```powershell function Show-Something { Write-Host 'show something on screen' } ``` -------------------------------- ### Function With SupportsShouldProcess Enabled Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseShouldProcessForStateChangingFunctions.md This example demonstrates the correct implementation of SupportsShouldProcess in a function's CmdletBinding attribute. This enables the Confirm and WhatIf parameters for state-changing operations. ```powershell function Set-ServiceObject { [CmdletBinding(SupportsShouldProcess = $true)] param ( [string] $Parameter1 ) ... } ``` -------------------------------- ### Format Script with Custom Hashtable Settings Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Cmdlets/Invoke-Formatter.md Apply specific formatting rules by providing a hashtable to the -Settings parameter. This example enables and configures rules for brace placement and indentation. ```powershell $scriptDefinition = @' function foo { "hello" } '@ $settings = @{ IncludeRules = @("PSPlaceOpenBrace", "PSUseConsistentIndentation") Rules = @{ PSPlaceOpenBrace = @{ Enable = $true OnSameLine = $false } PSUseConsistentIndentation = @{ Enable = $true } } } Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings ``` -------------------------------- ### DSC Resource With Verbose Output Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCUseVerboseMessageInDSCResource.md This example demonstrates a DSC resource function that correctly implements verbose output using `Write-Verbose`. This adheres to the best practice for providing user information. ```powershell Function Test-Function { [CmdletBinding()] Param() Write-Verbose 'Verbose output' ... } ``` -------------------------------- ### DSC Resource MOF Definition Example Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCUseIdenticalMandatoryParametersForDSC.md Defines a DSC resource with 'Name' as a key property and 'NodeName' as a required property. ```powershell class WaitForAny : OMI_BaseResource { [key, Description("Name of Resource on remote machine")] string Name; [required, Description("List of remote machines")] string NodeName[]; }; ``` -------------------------------- ### DSC Class Resource Functions (Correct) Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCStandardDSCFunctionsInResource.md Presents a correctly implemented class-based DSC resource with Get, Set, and Test methods. ```powershell [DscResource()] class MyDSCResource { [DscProperty(Key)] [string] $Name [MyDSCResource] Get() { ... } [void] Set() { ... } [bool] Test() { ... } } ``` -------------------------------- ### Run PSScriptAnalyzer Tests Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md Execute the PSScriptAnalyzer tests using the build script. Ensure Pester version 5.3 or higher is installed. ```powershell ./build -Test ``` -------------------------------- ### Unaligned Hashtable and Enum Example Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AlignAssignmentStatement.md Demonstrates a hashtable and an enum definition that are not aligned, illustrating the need for the AlignAssignmentStatement rule. ```powershell $hashtable = @{ property = 'value' anotherProperty = 'another value' } enum Enum { member = 1 anotherMember = 2 } ``` -------------------------------- ### Avoid Write-Host in Functions Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingWriteHost.md This example shows the incorrect use of Write-Host for general output. Replace Write-Host with Write-Output or Write-Verbose for pipeline-compatible output. ```powershell function Get-MeaningOfLife { Write-Host 'Computing the answer to the ultimate question of life, the universe and everything' Write-Host 42 } ``` -------------------------------- ### Configure PSScriptAnalyzer with a settings profile file Source: https://context7.com/powershell/psscriptanalyzer/llms.txt Uses a settings profile file (e.g., PSASettings.psd1) to configure rules for analysis. The example settings file specifies severity levels and includes/excludes rules. ```powershell # Use a settings profile file to configure rules # In .\PSASettings.psd1: # @{ Severity = @('Error','Warning'); IncludeRules = 'PSAvoid*'; ExcludeRules = '*WriteHost' } Invoke-ScriptAnalyzer -Path .\MyModule -Settings .\PSASettings.psd1 ``` -------------------------------- ### Valid Module Manifest with ModuleVersion Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/MissingModuleManifestField.md This example demonstrates a valid module manifest that includes the required `ModuleVersion` field. This is the correct structure for a module manifest. ```powershell @{ ModuleVersion = '1.0' Author = 'PowerShell Author' NestedModules = @('.\mymodule.psm1') FunctionsToExport = '*' CmdletsToExport = '*' VariablesToExport = '*' } ``` -------------------------------- ### Provide Settings Object to Invoke-ScriptAnalyzer Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseCompatibleTypes.md This example demonstrates how to create a settings object for PSScriptAnalyzer to enable the PSUseCompatibleTypes rule and specify target profiles, then use it with Invoke-ScriptAnalyzer. ```powershell PS> $settings = @{ Rules = @{ PSUseCompatibleTypes = @{ Enable = $true TargetProfiles = @('win-48_x64_10.0.17763.0_5.1.17763.316_x64_4.0.30319.42000_framework') } } } PS> Invoke-ScriptAnalyzer -Settings $settings -ScriptDefinition "[System.Management.Automation.SemanticVersion]'1.18.0-rc1'" RuleName Severity ScriptName Line Message -------- -------- ---------- ---- ------- PSUseCompatibleTypes Warning 1 The type 'System.Management.Automation.SemanticVersion' is not available by default in PowerShell version '5.1.17763.316' on platform 'Microsoft Windows 10 Pro' ``` -------------------------------- ### DSC Non-Class Resource Functions (Correct) Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCStandardDSCFunctionsInResource.md Shows a correctly implemented non-class based DSC resource including Get, Set, and Test-TargetResource functions. ```powershell function Get-TargetResource { [OutputType([Hashtable])] param ( [parameter(Mandatory = $true)] [String] $Name ) ... } function Set-TargetResource { param ( [parameter(Mandatory = $true)] [String] $Name ) ... } function Test-TargetResource { [OutputType([System.Boolean])] param ( [parameter(Mandatory = $true)] [String] $Name ) ... } ``` -------------------------------- ### Correct Function Handling Pipeline Input Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseProcessBlockForPipelineCommand.md This example demonstrates the correct way to handle pipeline input in a PowerShell function by using the 'process' block. This ensures that each item piped to the function is processed individually. ```powershell Function Get-Number { [CmdletBinding()] Param( [Parameter(ValueFromPipeline)] [int] $Number ) process { $Number } } ``` -------------------------------- ### Incorrect Use of Positional Parameters Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingPositionalParameters.md This example demonstrates the incorrect usage of positional parameters, which can lead to reduced readability and potential errors. ```powershell Get-Command ChildItem Microsoft.PowerShell.Management ``` -------------------------------- ### Example: Inline Parameters Incorrect Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseConsistentParametersKind.md Shows an incorrect usage of parameter definition when the rule expects the 'Inline' style, but 'ParamBlock' is used instead. ```powershell # Incorrect function g { param([Parameter()]$FirstParam) return } ``` -------------------------------- ### Using $using: with Start-ThreadJob and Start-Job Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseUsingScopeModifierInNewRunspaces.md Provides examples of correctly using the `$using:` scope modifier to access parent scope variables within scriptblocks for Start-ThreadJob and Start-Job. ```powershell $foo = 'foo' Start-ThreadJob -ScriptBlock { $using:foo } Start-Job -ScriptBlock {$using:foo } ``` -------------------------------- ### Module Manifest Missing ModuleVersion Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/MissingModuleManifestField.md This example shows a module manifest missing the required `ModuleVersion` field. Add `ModuleVersion` to ensure the manifest is valid. ```powershell @{ Author = 'PowerShell Author' NestedModules = @('.\mymodule.psm1') FunctionsToExport = '*' CmdletsToExport = '*' VariablesToExport = '*' } ``` -------------------------------- ### DSC Resource Without Verbose Output Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCUseVerboseMessageInDSCResource.md This example shows a DSC resource function that does not include verbose output. It is flagged as incorrect according to the best practice. ```powershell Function Test-Function { [CmdletBinding()] Param() ... } ``` -------------------------------- ### Correct Use of ValueFromPipeline Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseSingleValueFromPipelineParameter.md This corrected example shows a function where only one parameter accepts pipeline input by value, while the other is mandatory, adhering to the rule. ```powershell function Process-Data { [CmdletBinding()] param( [Parameter(ValueFromPipeline)] [string] $InputData, [Parameter(Mandatory)] [string] $ProcessingMode ) process { Write-Output "$ProcessingMode`: $InputData" } } ``` -------------------------------- ### Correct PowerShell code without semicolons Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidSemicolonsAsLineTerminators.md These examples demonstrate the correct way to write PowerShell code, avoiding unnecessary semicolons at the end of lines. ```powershell Install-Module -Name PSScriptAnalyzer; $a = 1 + $b ``` ```powershell Install-Module -Name PSScriptAnalyzer $a = 1 + $b ``` -------------------------------- ### Get DSC Rules with Error Severity Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Cmdlets/Get-ScriptAnalyzerRule.md This example demonstrates how to filter for specific types of rules (DSC) with a particular severity (Error) and then use them with Invoke-ScriptAnalyzerRule. It highlights the efficiency of using IncludeRule over Severity for Invoke-ScriptAnalyzerRule. ```powershell $DSCError = Get-ScriptAnalyzerRule -Severity Error | Where-Object SourceName -eq PSDSC $Path = "$home\Documents\WindowsPowerShell\Modules\MyDSCModule\*" Invoke-ScriptAnalyzerRule -Path $Path -IncludeRule $DSCError -Recurse ``` -------------------------------- ### GitHub Actions / Azure Pipelines Inline Step for PSScriptAnalyzer Source: https://context7.com/powershell/psscriptanalyzer/llms.txt An inline PowerShell step for CI/CD pipelines to install PSScriptAnalyzer, run analysis, and fail the build if errors are found. Ensures module quality before deployment. ```powershell # In a PowerShell step: Install-Module PSScriptAnalyzer -Force -SkipPublisherCheck $results = Invoke-ScriptAnalyzer -Path . -Recurse -Settings PSGallery -ReportSummary $errors = $results | Where-Object Severity -eq Error if ($errors) { $errors | Format-Table RuleName, ScriptName, Line, Message -AutoSize throw "PSScriptAnalyzer found $($errors.Count) error(s)." } ``` -------------------------------- ### Correct Usage of Mandatory Parameter Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidDefaultValueForMandatoryParameter.md This example demonstrates the correct way to define a mandatory parameter without a default value. The function will prompt for '$Parameter1' if it's not supplied during invocation. ```powershell function Test { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] $Parameter1 ) } ``` -------------------------------- ### Correct Cmdlet Verb Usage Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseApprovedVerbs.md This example demonstrates the correct way to name a cmdlet function using an approved verb ('Update'). Always use approved verbs for your cmdlets. ```powershell function Update-Item { ... } ``` -------------------------------- ### Build All Versions and Documentation Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md This command builds the module for all supported PowerShell versions (v5 and v7) and also rebuilds the documentation. ```powershell ./build.ps1 -All ``` -------------------------------- ### DSC Class Resource Function Return Types (Wrong) Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCReturnCorrectTypesForDSCFunctions.md Demonstrates incorrect return types for Get, Set, and Test methods in a class-based DSC resource. The Get method should return an instance of the DSC class, Set should return void, and Test should return a boolean. ```powershell [DscResource()] class MyDSCResource { [DscProperty(Key)] [string] $Name [String] Get() { ... } [String] Set() { ... } [bool] Test() { ... } } ``` -------------------------------- ### Invoke-ScriptAnalyzer with Settings Preset Source: https://github.com/powershell/psscriptanalyzer/blob/main/CHANGELOG.MD Demonstrates how to use a built-in settings preset like 'PSGallery' with Invoke-ScriptAnalyzer. Ensure the path to your module is correctly specified. ```powershell PS> Invoke-ScriptAnalyzer -Path /path/to/your/module -Settings PSGallery ``` -------------------------------- ### Get Rules by Severity Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Cmdlets/Get-ScriptAnalyzerRule.md Filters and retrieves script analyzer rules that have a specific severity level, such as 'Error'. ```powershell Get-ScriptAnalyzerRule -Severity Error ``` -------------------------------- ### Correct Cmdlet Noun Usage Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseSingularNouns.md This example demonstrates a cmdlet using a singular noun, adhering to the PSUseSingularNouns rule. ```powershell function Get-File { ... } ``` -------------------------------- ### Incorrect Cmdlet Noun Usage Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseSingularNouns.md This example shows a cmdlet using a plural noun, which violates the PSUseSingularNouns rule. ```powershell function Get-Files { ... } ``` -------------------------------- ### Navigate to Source Directory Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md Change your current directory to the cloned PSScriptAnalyzer repository. ```powershell cd path/to/PSScriptAnalyzer ``` -------------------------------- ### Incorrect PowerShell code with semicolons Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidSemicolonsAsLineTerminators.md These examples show incorrect usage where lines are terminated with semicolons, which this rule aims to prevent. ```powershell Install-Module -Name PSScriptAnalyzer; $a = 1 + $b; ``` ```powershell Install-Module -Name PSScriptAnalyzer; $a = 1 + $b ``` -------------------------------- ### Get All Script Analyzer Rules Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Cmdlets/Get-ScriptAnalyzerRule.md Retrieves all available script analyzer rules on the local system. This is the most basic usage of the cmdlet. ```powershell Get-ScriptAnalyzerRule ``` -------------------------------- ### Incorrect OutputType Declaration Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseOutputTypeCorrectly.md This example shows a function where the OutputType is declared as [String], but the function returns an integer (4). This violates the rule. ```powershell function Get-Foo { [CmdletBinding()] [OutputType([String])] Param( ) return 4 } ``` -------------------------------- ### Use SupportsShouldProcess for WhatIf/Confirm Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseSupportsShouldProcess.md Use the CmdletBinding attribute with SupportsShouldProcess to automatically include $WhatIf and $Confirm parameters and their functionality. ```powershell function foo { [CmdletBinding(SupportsShouldProcess)] param( $param1 ) } ``` -------------------------------- ### Example: ParamBlock Parameters Incorrect Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseConsistentParametersKind.md Illustrates an incorrect parameter definition when the rule is set to enforce 'ParamBlock' style, but 'Inline' is used. ```powershell # Incorrect function f([Parameter()]$FirstParam) { return } ``` -------------------------------- ### Get PSScriptAnalyzer rules by severity Source: https://context7.com/powershell/psscriptanalyzer/llms.txt Retrieves PSScriptAnalyzer rules filtered by specified severity levels (e.g., Error, Warning, Information). ```powershell # Get rules by severity Get-ScriptAnalyzerRule -Severity Error Get-ScriptAnalyzerRule -Severity Warning, Information ``` -------------------------------- ### Configure PSProvideCommentHelp Rule Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/ProvideCommentHelp.md This snippet shows how to configure the PSProvideCommentHelp rule, including enabling it, setting it to only check exported members, choosing between block or line comment style, and specifying the placement of the help comments. ```powershell Rules = @{ PSProvideCommentHelp = @{ Enable = $true ExportedOnly = $false BlockComment = $true VSCodeSnippetCorrection = $false Placement = 'before' } } ``` -------------------------------- ### Analyze an inline script string with PSScriptAnalyzer Source: https://context7.com/powershell/psscriptanalyzer/llms.txt Analyzes a script provided as a string, useful for CI pipelines or editors. Shows an example output. ```powershell # Analyze an inline script string (useful in CI pipelines or editors) Invoke-ScriptAnalyzer -ScriptDefinition "function Get-Foo { dir `$pshome }" # Output: # RuleName Severity FileName Line Message # -------- -------- -------- ---- ------- # PSAvoidUsingCmdletAliases Warning 1 'dir' is an alias of 'Get-ChildItem'... ``` -------------------------------- ### Correct Switch Parameter Handling Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidDefaultValueSwitchParameter.md Shows the correct way to define and handle a switch parameter. It defaults to $false if not explicitly provided by checking $PSBoundParameters. ```powershell function Test-Script { [CmdletBinding()] Param ( [String] $Param1, [switch] $Switch ) begin { # Ensure that the $Switch is set to false if not provided if (-not $PSBoundParameters.ContainsKey('Switch')) { $Switch = $false } } ... } ``` -------------------------------- ### Correct DSC TargetResource Functions Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCUseIdenticalMandatoryParametersForDSC.md Shows correct implementations of Get-TargetResource, Set-TargetResource, and Test-TargetResource where mandatory parameters align with MOF key/required properties. ```powershell function Get-TargetResource { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $Message, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $Name ) } function Set-TargetResource { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $Message, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $Name ) } function Test-TargetResource { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $Message, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $Name ) } ``` -------------------------------- ### Correct OutputType Declaration Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseOutputTypeCorrectly.md This example demonstrates a function where the OutputType is correctly declared as [String], and the function returns a string ('four'), adhering to the rule. ```powershell function Get-Foo { [CmdletBinding()] [OutputType([String])] Param( ) return 'four' } ``` -------------------------------- ### Create Release Build Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md Use the ReleaseMaker module to create a release build. This updates manifests, project files, and generates a release in the 'out/' directory. ```powershell Import-Module .\Utils\ReleaseMaker.psm1 New-Release ``` -------------------------------- ### Avoid Manual WhatIf/Confirm Parameters Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseSupportsShouldProcess.md Manually declaring $Confirm and $WhatIf parameters is discouraged. Use CmdletBinding with SupportsShouldProcess instead. ```powershell function foo { param( $param1, $Confirm, $WhatIf ) } ``` -------------------------------- ### Example of Unused Parameter in PowerShell Function Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/ReviewUnusedParameter.md This snippet demonstrates a function with an unused parameter (`$Parameter2`). Consider removing such parameters to improve code clarity. ```powershell function Test-Parameter { Param ( $Parameter1, # this parameter is never called in the function $Parameter2 ) Get-Something $Parameter1 } ``` -------------------------------- ### Clone PSScriptAnalyzer Repository Source: https://github.com/powershell/psscriptanalyzer/blob/main/README.md Use this command to download the source code from the GitHub repository. ```powershell git clone https://github.com/PowerShell/PSScriptAnalyzer ``` -------------------------------- ### Correct ShouldProcess Implementation Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/ShouldProcess.md Use this snippet as a reference for correctly implementing ShouldProcess. It demonstrates declaring SupportsShouldProcess and conditionally executing the core logic within an if block that calls $PSCmdlet.ShouldProcess. ```powershell function Set-File { [CmdletBinding(SupportsShouldProcess=$true)] Param ( # Path to file [Parameter(Mandatory=$true)] $Path, [Parameter(Mandatory=$true)] [string]$Content ) if ($PSCmdlet.ShouldProcess($Path, ("Setting content to '{0}'" -f $Content))) { $Content | Out-File -FilePath $Path } else { # Code that should be processed if doing a WhatIf operation # Must NOT change anything outside of the function / script } } ``` -------------------------------- ### Configure PSUseConsistentIndentation Rule Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseConsistentIndentation.md This configuration enables the PSUseConsistentIndentation rule and sets its parameters. Adjust IndentationSize, PipelineIndentation, and Kind according to your project's coding standards. ```powershell Rules = @{ PSUseConsistentIndentation = @{ Enable = $true IndentationSize = 4 PipelineIndentation = 'IncreaseIndentationForFirstPipeline' Kind = 'space' } } ``` -------------------------------- ### Get PSScriptAnalyzer rules by name pattern Source: https://context7.com/powershell/psscriptanalyzer/llms.txt Retrieves PSScriptAnalyzer rules whose names match a given wildcard pattern, optionally filtered by severity. ```powershell # Get rules whose name matches a wildcard pattern Get-ScriptAnalyzerRule -Name PSAvoid* Get-ScriptAnalyzerRule -Name *Parameter*, *Alias* -Severity Error, Warning ``` -------------------------------- ### Load and list custom PSScriptAnalyzer rules Source: https://context7.com/powershell/psscriptanalyzer/llms.txt Loads custom rules from a specified directory (recursively) and lists them. ```powershell # Load and list custom rules from a directory (recursive) Get-ScriptAnalyzerRule -CustomRulePath C:\MyCustomRules -RecurseCustomRulePath ``` -------------------------------- ### Configure PSUseCompatibleCommands Rule Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseCompatibleCommands.md Use this configuration to enable the rule and specify target PowerShell profiles, including custom paths and names. You can also list commands to ignore for compatibility checks. ```powershell @{ Rules = @{ PSUseCompatibleCommands = @{ Enable = $true TargetProfiles = @( 'ubuntu_x64_18.04_6.1.3_x64_4.0.30319.42000_core' 'win-48_x64_10.0.17763.0_5.1.17763.316_x64_4.0.30319.42000_framework' 'MyProfile' 'another_custom_profile_in_the_profiles_directory.json' 'D:\My Profiles\profile1.json' ) # You can specify commands to not check like this, which also will ignore its parameters: IgnoreCommands = @( 'Install-Module' ) } } } ``` -------------------------------- ### Incorrect Use of ValueFromPipeline Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/UseSingleValueFromPipelineParameter.md This example demonstrates a function with two parameters, both set to accept pipeline input by value within the same parameter set, violating the rule. ```powershell function Process-Data { [CmdletBinding()] param( [Parameter(ValueFromPipeline)] [string] $InputData, [Parameter(ValueFromPipeline)] [string] $ProcessingMode ) process { Write-Output "$ProcessingMode`: $InputData" } } ``` -------------------------------- ### Use PSCredential Parameter (Correct) Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingUsernameAndPasswordParams.md This snippet shows the correct way to define a parameter for credentials using the PSCredential type. This promotes standardization and security. ```powershell function Test-Script { [CmdletBinding()] Param ( [PSCredential] $Credential ) ... } ``` -------------------------------- ### Avoid Cmdlet Aliases Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/AvoidUsingCmdletAliases.md Use the full cmdlet name instead of an alias for better script readability and maintainability. This example shows replacing 'gps' with 'Get-Process'. ```powershell gps | Where-Object {$_.WorkingSet -gt 20000000} ``` -------------------------------- ### Correct DSC Resource Parameters Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Rules/DSCUseIdenticalParametersForDSC.md Illustrates a DSC resource where Get-TargetResource, Set-TargetResource, and Test-TargetResource functions correctly share identical parameters. This adheres to the DSC best practice for parameter consistency. ```powershell function Get-TargetResource { [OutputType([Hashtable])] param ( [parameter(Mandatory = $true)] [String] $Name, [String] $TargetResource ) ... } function Set-TargetResource { param ( [parameter(Mandatory = $true)] [String] $Name, [String] $TargetResource ) ... } function Test-TargetResource { [OutputType([System.Boolean])] param ( [parameter(Mandatory = $true)] [String] $Name, [String] $TargetResource ) ... } ``` -------------------------------- ### Configure PSScriptAnalyzer with an inline settings hashtable Source: https://context7.com/powershell/psscriptanalyzer/llms.txt Applies rule configurations using a hashtable directly within the command. Includes specific rules and severity levels. ```powershell # Use a hashtable as inline settings Invoke-ScriptAnalyzer -Path .\MyScript.ps1 -Settings @{ IncludeRules = @('PSAvoidUsingWriteHost', 'PSAvoidUsingCmdletAliases') Severity = @('Warning', 'Error') } ``` -------------------------------- ### Analyze Script Files Using a Profile Definition Source: https://github.com/powershell/psscriptanalyzer/blob/main/docs/Cmdlets/Invoke-ScriptAnalyzer.md Create a Script Analyzer profile in a text file to define severity, included rules, and excluded rules. Use the -Settings parameter to apply the profile during analysis. ```powershell # In .\ScriptAnalyzerProfile.txt @{ Severity = @('Error', 'Warning') IncludeRules = 'PSAvoid*' ExcludeRules = '*WriteHost' } Invoke-ScriptAnalyzer -Path $pshome\Modules\BitLocker -Settings .\ScriptAnalyzerProfile.txt ```