Suppressing rules

It is rarely realistic to expect any significant piece of code to pass all of the tests that PSScriptAnalyzer will throw at it.

Individual tests can be suppressed at the function, script, or class level. The following demonstrative function creates a PSCustomObject:

function New-Message { 
    [CmdletBinding()] 
    param ( 
        $Message 
    ) 
 
    [PSCustomObject]@{ 
        Name  = 1 
        Value = $Message 
    } 
} 

Running PSScriptAnalyzer against a file containing the function will show the following warning:

PS> Invoke-ScriptAnalyzer -Path .New-Message.ps1 | Format-List

RuleName : PSUseShouldProcessForStateChangingFunctions
Severity : Warning
Line : 1
Column : 10
Message : Function 'New-Message' has verb that could change system state. Therefore, the function
has to support 'ShouldProcess'.

Given that this function creates a new object in the memory, and does not change the system state, the message might be suppressed. This is achieved by adding a SuppressMessage attribute before a param block:

function New-Message { 
    [Diagnostics.CodeAnalysis.SuppressMessage(
'PSUseShouldProcessForStateChangingFunctions',
''
)] [CmdletBinding()] param ( $Message ) [PSCustomObject]@{ Name = 1 Value = $Message } }
VS Code snippets

VS Code will offer to automatically complete the suppress message attribute when starting to type the word suppress.

Rules are often suppressed as it becomes evident one will be triggered. The list of rules may be viewed using the Get-ScriptAnalyzerRule command.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.199.243