Skip to content

Update rule docs #1711

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Sep 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ usage of Invoke-Expression etc. Additional functionalities such as exclude/inclu
Usage
======================

``` PowerShell
```powershell
Get-ScriptAnalyzerRule [-CustomRulePath <String[]>] [-RecurseCustomRulePath] [-Name <String[]>] [-Severity <String[]>] [<CommonParameters>]

Invoke-ScriptAnalyzer [-Path] <String> [-CustomRulePath <String[]>] [-RecurseCustomRulePath]
Expand Down Expand Up @@ -188,7 +188,7 @@ Pester-based ScriptAnalyzer Tests are located in `path/to/PSScriptAnalyzer/Tests

* Ensure [Pester 4.3.1](https://www.powershellgallery.com/packages/Pester/4.3.1) or higher is installed
* In the root folder of your local repository, run:
``` PowerShell
```powershell
./build -Test
```

Expand Down Expand Up @@ -251,7 +251,7 @@ Suppressing Rules
You can suppress a rule by decorating a script/function or script/function parameter with .NET's [SuppressMessageAttribute](https://docs.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.suppressmessageattribute).
`SuppressMessageAttribute`'s constructor takes two parameters: a category and a check ID. Set the `categoryID` parameter to the name of the rule you want to suppress and set the `checkID` parameter to a null or empty string. You can optionally add a third named parameter with a justification for suppressing the message:

``` PowerShell
```powershell
function SuppressMe()
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSProvideCommentHelp', '', Justification='Just an example')]
Expand All @@ -265,7 +265,7 @@ function SuppressMe()
All rule violations within the scope of the script/function/parameter you decorate will be suppressed.

To suppress a message on a specific parameter, set the `SuppressMessageAttribute`'s `CheckId` parameter to the name of the parameter:
``` PowerShell
```powershell
function SuppressTwoVariables()
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSProvideDefaultParameterValue', 'b')]
Expand All @@ -280,7 +280,7 @@ Use the `SuppressMessageAttribute`'s `Scope` property to limit rule suppression

Use the value `Function` to suppress violations on all functions within the attribute's scope. Use the value `Class` to suppress violations on all classes within the attribute's scope:

``` PowerShell
```powershell
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSProvideCommentHelp', '', Scope='Function')]
param(
)
Expand All @@ -296,7 +296,7 @@ function InternalFunction
You can further restrict suppression based on a function/parameter/class/variable/object's name by setting the `SuppressMessageAttribute's` `Target` property to a regular expression or a glob pattern. Few examples are given below.

Suppress `PSAvoidUsingWriteHost` rule violation in `start-bar` and `start-baz` but not in `start-foo` and `start-bam`:
``` PowerShell
```powershell
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Scope='Function', Target='start-ba[rz]')]
param()
function start-foo {
Expand All @@ -317,13 +317,13 @@ function start-bam {
```

Suppress violations in all the functions:
``` PowerShell
```powershell
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Scope='Function', Target='*')]
Param()
```

Suppress violation in `start-bar`, `start-baz` and `start-bam` but not in `start-foo`:
``` PowerShell
```powershell
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Scope='Function', Target='start-b*')]
Param()
```
Expand Down Expand Up @@ -354,7 +354,7 @@ Along with `PSGallery` there are a few other built-in presets, including, `DSC`
The following example excludes two rules from the default set of rules and any rule
that does not output an Error or Warning diagnostic record.

``` PowerShell
```powershell
# PSScriptAnalyzerSettings.psd1
@{
Severity=@('Error','Warning')
Expand All @@ -365,13 +365,13 @@ that does not output an Error or Warning diagnostic record.

Then invoke that settings file when using `Invoke-ScriptAnalyzer`:

``` PowerShell
```powershell
Invoke-ScriptAnalyzer -Path MyScript.ps1 -Settings PSScriptAnalyzerSettings.psd1
```

The next example selects a few rules to execute instead of all the default rules.

``` PowerShell
```powershell
# PSScriptAnalyzerSettings.psd1
@{
IncludeRules=@('PSAvoidUsingPlainTextForPassword',
Expand All @@ -380,15 +380,15 @@ The next example selects a few rules to execute instead of all the default rules
```

Then invoke that settings file:
``` PowerShell
```powershell
Invoke-ScriptAnalyzer -Path MyScript.ps1 -Settings PSScriptAnalyzerSettings.psd1
```

### Implicit

If you place a PSScriptAnayzer settings file named `PSScriptAnalyzerSettings.psd1` in your project root, PSScriptAnalyzer will discover it if you pass the project root as the `Path` parameter.

```PowerShell
```powershell
Invoke-ScriptAnalyzer -Path "C:\path\to\project" -Recurse
```

Expand Down
23 changes: 14 additions & 9 deletions RuleDocumentation/AlignAssignmentStatement.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

## Description

Consecutive assignment statements are more readable if they are aligned. By aligned, we imply that the `equal` sign for all the assignment statements should be in the same column.
Consecutive assignment statements are more readable if they are aligned. By aligned, we imply that
the `equal` sign for all the assignment statements should be in the same column.

The rule looks for key (property) value pairs in a hashtable (DSC configuration) to check if they are aligned or not. Consider the following example in which the key value pairs are not aligned.
The rule looks for key (property) value pairs in a hashtable (DSC configuration) to check if they
are aligned or not. Consider the following example in which the key value pairs are not aligned.

```powershell
$hashtable = @{
Expand All @@ -24,17 +26,18 @@ $hashtable = @{
}
```

The rule will ignore hashtables in which the assignment statements are on the same line. For example, the rule will ignore `$h = {a = 1; b = 2}`.
The rule ignores hashtables in which the assignment statements are on the same line. For example,
the rule ignores `$h = {a = 1; b = 2}`.

## Configuration

```powershell
Rules = @{
PSAlignAssignmentStatement = @{
Enable = $true
CheckHashtable = $true
}
Rules = @{
PSAlignAssignmentStatement = @{
Enable = $true
CheckHashtable = $true
}
}
```

### Parameters
Expand All @@ -45,4 +48,6 @@ Enable or disable the rule during ScriptAnalyzer invocation.

#### CheckHashtable: bool (Default value is `$false`)

Enforce alignment of assignment statements in a hashtable and in a DSC Configuration. There is only one switch for hasthable and DSC configuration because the property value pairs in a DSC configuration are parsed as key value pairs of a hashtable.
Enforce alignment of assignment statements in a hashtable and in a DSC Configuration. There is only
one switch for hasthable and DSC configuration because the property value pairs in a DSC
configuration are parsed as key-value pairs of a hashtable.
15 changes: 9 additions & 6 deletions RuleDocumentation/AvoidAssignmentToAutomaticVariable.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

## Description

`PowerShell` exposes some of its built-in variables that are known as automatic variables. Many of them are read-only and PowerShell would throw an error when trying to assign an value on those. Other automatic variables should only be assigned to in certain special cases to achieve a certain effect as a special technique.
PowerShell has built-in variables known as automatic variables. Many of them are read-only and
PowerShell throws an error when trying to assign an value on those. Other automatic variables should
only be assigned in certain special cases to achieve a certain effect as a special technique.

To understand more about automatic variables, see ```Get-Help about_Automatic_Variables```.
To understand more about automatic variables, see `Get-Help about_Automatic_Variables`.

## How

Expand All @@ -16,18 +18,19 @@ Use variable names in functions or their parameters that do not conflict with au

### Wrong

The variable `$Error` is an automatic variables that exists in the global scope and should therefore never be used as a variable or parameter name.
The variable `$Error` is an automatic variables that exists in the global scope and should therefore
never be used as a variable or parameter name.

``` PowerShell
```powershell
function foo($Error){ }
```

``` PowerShell
```powershell
function Get-CustomErrorMessage($ErrorMessage){ $Error = "Error occurred: $ErrorMessage" }
```

### Correct

``` PowerShell
```powershell
function Get-CustomErrorMessage($ErrorMessage){ $FinalErrorMessage = "Error occurred: $ErrorMessage" }
```
8 changes: 5 additions & 3 deletions RuleDocumentation/AvoidDefaultValueForMandatoryParameter.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

## Description

Mandatory parameters should not have a default values because there is no scenario where the default can be used because `PowerShell` will prompt anyway if the parameter value is not specified when calling the function.
Mandatory parameters should not have a default values because there is no scenario where the default
can be used. PowerShell prompts for a value if the parameter value is not specified when calling the
function.

## Example

### Wrong

``` PowerShell
```powershell
function Test
{

Expand All @@ -25,7 +27,7 @@ function Test

### Correct

``` PowerShell
```powershell
function Test
{
[CmdletBinding()]
Expand Down
4 changes: 2 additions & 2 deletions RuleDocumentation/AvoidDefaultValueSwitchParameter.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Change the default value of the switch parameter to be false.

### Wrong

``` PowerShell
```powershell
function Test-Script
{
[CmdletBinding()]
Expand All @@ -32,7 +32,7 @@ function Test-Script

### Correct

``` PowerShell
```powershell
function Test-Script
{
[CmdletBinding()]
Expand Down
12 changes: 7 additions & 5 deletions RuleDocumentation/AvoidGlobalAliases.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

## Description

Globally scoped aliases override existing aliases within the sessions with matching names. This name collision can cause difficult to debug issues for consumers of modules and scripts.
Globally scoped aliases override existing aliases within the sessions with matching names. This name
collision can cause difficult to debug issues for consumers of modules and scripts.

To understand more about scoping, see ```Get-Help about_Scopes```.
To understand more about scoping, see `Get-Help about_Scopes`.

**NOTE** This rule is not available in PowerShell version 3 and 4 due to the `StaticParameterBinder.BindCommand` API that the rule uses internally.
**NOTE** This rule is not available in PowerShell version 3 or 4 because it uses the
`StaticParameterBinder.BindCommand` API.

## How

Expand All @@ -18,12 +20,12 @@ Use other scope modifiers for new aliases.

### Wrong

``` PowerShell
```powershell
New-Alias -Name Name -Value Value -Scope "Global"
```

### Correct

``` PowerShell
```powershell
New-Alias -Name Name1 -Value Value
```
11 changes: 6 additions & 5 deletions RuleDocumentation/AvoidGlobalFunctions.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@

## Description

Globally scoped functions override existing functions within the sessions with matching names. This name collision can cause difficult to debug issues for consumers of modules.
Globally scoped functions override existing functions within the sessions with matching names. This
name collision can cause difficult to debug issues for consumers of modules.


To understand more about scoping, see ```Get-Help about_Scopes```.
To understand more about scoping, see `Get-Help about_Scopes`.

## How

Expand All @@ -17,12 +18,12 @@ Use other scope modifiers for functions.

### Wrong

``` PowerShell
```powershell
function global:functionName {}
```

### Correct

``` PowerShell
function functionName {}
```powershell
function functionName {}
```
22 changes: 12 additions & 10 deletions RuleDocumentation/AvoidGlobalVars.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@

## Description

A variable is a unit of memory in which values are stored. Windows PowerShell controls access to variables, functions, aliases, and drives through a mechanism known as scoping.
Variables and functions that are present when Windows PowerShell starts have been created in the global scope.
A variable is a unit of memory in which values are stored. PowerShell controls access to variables,
functions, aliases, and drives through a mechanism known as scoping. Variables and functions that
are present when PowerShell starts have been created in the global scope.

Globally scoped variables include:
* Automatic variables
* Preference variables
* Variables, aliases, and functions that are in your Windows PowerShell profiles

To understand more about scoping, see ```Get-Help about_Scopes```.
- Automatic variables
- Preference variables
- Variables, aliases, and functions that are in your PowerShell profiles

To understand more about scoping, see `Get-Help about_Scopes`.

## How

Expand All @@ -22,20 +24,20 @@ Use other scope modifiers for variables.

### Wrong

``` PowerShell
```powershell
$Global:var1 = $null
function Test-NotGlobal ($var)
{
$a = $var + $var1
$a = $var + $var1
}
```

### Correct

``` PowerShell
```powershell
$var1 = $null
function Test-NotGlobal ($var1, $var2)
{
$a = $var1 + $var2
$a = $var1 + $var2
}
```
7 changes: 4 additions & 3 deletions RuleDocumentation/AvoidInvokingEmptyMembers.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

## Description

Invoking non-constant members can cause potential bugs. Please double check the syntax to make sure that invoked members are constants.
Invoking non-constant members can cause potential bugs. Please double check the syntax to make sure
that invoked members are constants.

## How

Expand All @@ -14,14 +15,14 @@ Provide the requested members for a given type or class.

### Wrong

``` PowerShell
```powershell
$MyString = "abc"
$MyString.('len'+'gth')
```

### Correct

``` PowerShell
```powershell
$MyString = "abc"
$MyString.('length')
```
Loading