From 33d13a41dcb334e4316e3848700a768dfa236ce5 Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Thu, 4 Jun 2026 10:32:33 -0400 Subject: [PATCH 1/4] [Freshness] PSScriptAnalyzer Article Updates - Batch 1 (#401) * Freshness * Add AvoidExclaimOperator to TOC * Heading edit * Reintroduce params * Applied feedback * Applied feedback * Fix param * Applied 'This rule... construction' feedback --- .../Rules/AvoidExclaimOperator.md | 27 +++++++++------- .../Rules/AvoidGlobalAliases.md | 27 +++++++++------- .../Rules/AvoidGlobalFunctions.md | 21 +++++++------ .../PSScriptAnalyzer/Rules/AvoidGlobalVars.md | 31 ++++++++++++------- .../Rules/AvoidInvokingEmptyMembers.md | 22 +++++++------ reference/docs-conceptual/toc.yml | 2 ++ 6 files changed, 78 insertions(+), 52 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidExclaimOperator.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidExclaimOperator.md index 11d078d6..dcd2cf96 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidExclaimOperator.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidExclaimOperator.md @@ -1,6 +1,6 @@ --- description: Avoid exclaim operator -ms.date: 03/26/2024 +ms.date: 05/28/2026 ms.topic: reference title: AvoidExclaimOperator --- @@ -10,28 +10,32 @@ title: AvoidExclaimOperator ## Description -Avoid using the negation operator (`!`). Use `-not` for improved readability. +This rule detects the use of the negation operator (an exclamation mark, `!`) and recommends using +the `-not` operator instead for improved readability and consistency with PowerShell conventions. -> [!NOTE] -> This rule is not enabled by default. The user needs to enable it through settings. +The `-not` operator is more explicit and aligns with PowerShell's verbose style, making code +easier to understand at a glance. -## How to Fix +This rule is **disabled** by default. Enable it explicitly during ScriptAnalyzer invocation if +desired. ## Example -### Wrong +### Noncompliant ```powershell $MyVar = !$true ``` -### Correct +### Compliant ```powershell $MyVar = -not $true ``` -## Configuration +## Configure rule + +To enable this rule, run the following command: ```powershell Rules = @{ @@ -41,8 +45,9 @@ Rules = @{ } ``` -### Parameters +## Parameters -- `Enable`: **bool** (Default value is `$false`) +### Enable - Enable or disable the rule during ScriptAnalyzer invocation. +This parameter controls whether ScriptAnalyzer checks the code against this rule. It accepts a +boolean value. To enable this rule, set this parameter to `$true`. The default value is `$false`. diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalAliases.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalAliases.md index 5157ec6f..2778e089 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalAliases.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalAliases.md @@ -1,6 +1,6 @@ --- -description: Avoid global aliases. -ms.date: 06/28/2023 +description: Avoid global aliases +ms.date: 05/28/2026 ms.topic: reference title: AvoidGlobalAliases --- @@ -10,28 +10,31 @@ title: AvoidGlobalAliases ## 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. +This rule detects the use of the `New-Alias` command to create aliases in the global scope. Global +aliases can unintentionally override existing aliases in the session, leading to unexpected behavior +and name collisions. Name collisions make it difficult for module consumers to diagnose issues and +maintain code reliability. -To understand more about scoping, see `Get-Help about_Scopes`. - -**NOTE** This rule is not available in PowerShell version 3 or 4 because it uses the +This rule is not available in PowerShell version 3 or 4 because it uses the `StaticParameterBinder.BindCommand` API. -## How - -Use other scope modifiers for new aliases. +To avoid this issue, define aliases without the **Scope** parameter, or use other appropriate scope +modifiers. To learn more, see [about_Scopes][01]. ## Example -### Wrong +### Noncompliant ```powershell New-Alias -Name Name -Value Value -Scope Global ``` -### Correct +### Compliant ```powershell New-Alias -Name Name1 -Value Value ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_scopes diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalFunctions.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalFunctions.md index 929466cb..c3c03d31 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalFunctions.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalFunctions.md @@ -10,25 +10,28 @@ title: AvoidGlobalFunctions ## 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. +This rule detects function definitions that use the `global:` scope modifier on the function name to +define a function in the global scope. Global functions can unintentionally override existing +functions in the session, leading to unexpected behavior and name collisions. Name collisions make +it difficult for module consumers to diagnose issues and maintain code reliability. -To understand more about scoping, see `Get-Help about_Scopes`. - -## How - -Use other scope modifiers for functions. +To avoid this issue, define functions without the global scope modifier, or use other appropriate +scope modifiers. To learn more, see [about_Scopes][01]. ## Example -### Wrong +### Noncompliant ```powershell function global:functionName {} ``` -### Correct +### Compliant ```powershell function functionName {} ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_scopes diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalVars.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalVars.md index 7fa0f6d2..add12c62 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalVars.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidGlobalVars.md @@ -1,6 +1,6 @@ --- -description: No Global Variables -ms.date: 06/28/2023 +description: Avoid global variables +ms.date: 05/28/2026 ms.topic: reference title: AvoidGlobalVars --- @@ -10,25 +10,28 @@ title: AvoidGlobalVars ## Description -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. +This rule detects usage of variables with the global scope modifier. 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 PowerShell profiles -To understand more about scoping, see `Get-Help about_Scopes`. +This rule doesn't detect use of the `New-Variable` cmdlet to create variables in the global scope or +the other `*-Variable` cmdlets to work with variables in the global scope. It only detects variable +expressions with the global scope modifier, like `$global:example`. -## How +This rule doesn't apply to variable expressions that use the global scope modifier where the +variable name is for an [automatic variable][01] or a [preference variable][02]. -Use other scope modifiers for variables. +Use local or script scope for variables instead of the global scope. To learn more, see +[about_Scopes][03]. ## Example -### Wrong +### Noncompliant ```powershell $Global:var1 = $null @@ -38,7 +41,7 @@ function Test-NotGlobal ($var) } ``` -### Correct +### Compliant ```powershell $var1 = $null @@ -47,3 +50,9 @@ function Test-NotGlobal ($var1, $var2) $a = $var1 + $var2 } ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_automatic_variables +[02]: /powershell/module/microsoft.powershell.core/about/about_preference_variables +[03]: /powershell/module/microsoft.powershell.core/about/about_scopes diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidInvokingEmptyMembers.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidInvokingEmptyMembers.md index 6049e869..4a737302 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidInvokingEmptyMembers.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidInvokingEmptyMembers.md @@ -1,6 +1,6 @@ --- -description: Avoid Invoking Empty Members -ms.date: 06/28/2023 +description: Avoid invoking empty members +ms.date: 05/28/2026 ms.topic: reference title: AvoidInvokingEmptyMembers --- @@ -10,25 +10,29 @@ title: AvoidInvokingEmptyMembers ## Description -Invoking non-constant members can cause potential bugs. Please double check the syntax to make sure -that invoked members are constants. +This rule detects expressions where the code uses the [member-access operator][01] (`.`) where the +member name is dynamically constructed. Invoking dynamically constructed member names can introduce +unexpected behavior and runtime errors. Ensure that member invocations use constant, literal member +names rather than expressions that are evaluated at runtime. -## How - -Provide the requested members for a given type or class. +Replace dynamic member name expressions with constant member names for the target type or class. ## Example -### Wrong +### Noncompliant ```powershell $MyString = 'abc' $MyString.('len'+'gth') ``` -### Correct +### Compliant ```powershell $MyString = 'abc' $MyString.('length') ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_operators#member-access-operator- diff --git a/reference/docs-conceptual/toc.yml b/reference/docs-conceptual/toc.yml index 1fbfbd36..7f05adaa 100644 --- a/reference/docs-conceptual/toc.yml +++ b/reference/docs-conceptual/toc.yml @@ -43,6 +43,8 @@ items: href: PSScriptAnalyzer/Rules/AvoidDefaultValueForMandatoryParameter.md - name: AvoidDefaultValueSwitchParameter href: PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md + - name: AvoidExclaimOperator + href: PSScriptAnalyzer/Rules/AvoidExclaimOperator.md - name: AvoidGlobalAliases href: PSScriptAnalyzer/Rules/AvoidGlobalAliases.md - name: AvoidGlobalFunctions From 35a6ce0ed6be0bdbf395c6b95d9180aabf20da44 Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Thu, 4 Jun 2026 10:47:06 -0400 Subject: [PATCH 2/4] [Freshness] PSScriptAnalyzer Article Updates - Batch 2 (#403) * Freshness * Fix validation * Minor edit * Update description * Applied feedback * Applied feedback * Apply suggestions from review Co-authored-by: Mikey Lombardi (He/Him) --------- Co-authored-by: Mikey Lombardi (He/Him) --- .../PSScriptAnalyzer/Rules/AvoidLongLines.md | 40 +++++++--- .../Rules/AvoidMultipleTypeAttributes.md | 18 ++--- .../AvoidNullOrEmptyHelpMessageAttribute.md | 22 ++--- .../Rules/AvoidOverwritingBuiltInCmdlets.md | 80 +++++++++++++------ .../AvoidReservedWordsAsFunctionNames.md | 17 ++-- 5 files changed, 114 insertions(+), 63 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidLongLines.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidLongLines.md index 89474c8b..d1c33b08 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidLongLines.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidLongLines.md @@ -1,6 +1,6 @@ --- description: Avoid long lines -ms.date: 03/20/2026 +ms.date: 06/01/2026 ms.topic: reference title: AvoidLongLines --- @@ -10,18 +10,32 @@ title: AvoidLongLines ## Description -The length of lines, including leading spaces (indentation), should be less than the configured -number of characters. The default length is 120 characters. +This rule detects lines that exceed the configured maximum length, including leading spaces +(indentation). The default maximum line length is 120 characters. This rule is **disabled** by +default and must be explicitly enabled through rule configuration settings. -> [!NOTE] -> This rule isn't enabled by default. The user needs to enable it through settings. +## Example -## Configuration +### Noncompliant + +``` +In this example of sample text, the maximum line length is using the default setting of not exceeding more than 120 +characters. +``` + +### Compliant + +``` +In this example of sample text, the maximum line length is set to not exceed +more than 80 characters. +``` + +## Configure rule ```powershell Rules = @{ - PSAvoidLongLines = @{ - Enable = $true + PSAvoidLongLines = @{ + Enable = $true MaximumLineLength = 120 } } @@ -29,10 +43,12 @@ Rules = @{ ## Parameters -### `Enable`: bool (Default value is `$false`) +### Enable -Enable or disable the rule during ScriptAnalyzer invocation. +This parameter controls whether ScriptAnalyzer checks the code against this rule. It accepts a +boolean value. To enable this rule, set this parameter to `$true`. The default value is `$false`. -### `MaximumLineLength`: int (Default value is 120) +### MaximumLineLength -Optional parameter to override the default maximum line length. +This parameter is optional and defines the maximum length for a line before it violates the rule. It +accepts an integer value. The default value is `120`. diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidMultipleTypeAttributes.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidMultipleTypeAttributes.md index 9ccd478c..d4fd2fda 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidMultipleTypeAttributes.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidMultipleTypeAttributes.md @@ -1,6 +1,6 @@ --- -description: Avoid multiple type specifiers on parameters. -ms.date: 06/28/2023 +description: Avoid multiple type specifiers on parameters +ms.date: 06/01/2026 ms.topic: reference title: AvoidMultipleTypeAttributes --- @@ -10,16 +10,16 @@ title: AvoidMultipleTypeAttributes ## Description -Parameters should not have more than one type specifier. Multiple type specifiers on parameters -can cause runtime errors. +This rule detects parameters that have multiple type specifiers applied to them. Parameters +shouldn't have multiple type specifiers. When you apply more than one type attribute to a parameter, +it can lead to unexpected type coercion or runtime errors. -## How - -Ensure each parameter has only 1 type specifier. +Each parameter should have exactly one type specifier to ensure predictable behavior and type +safety. ## Example -### Wrong +### Noncompliant ```powershell function Test-Script @@ -34,7 +34,7 @@ function Test-Script } ``` -### Correct +### Compliant ```powershell function Test-Script diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidNullOrEmptyHelpMessageAttribute.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidNullOrEmptyHelpMessageAttribute.md index 386c9605..5535f4b6 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidNullOrEmptyHelpMessageAttribute.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidNullOrEmptyHelpMessageAttribute.md @@ -1,6 +1,6 @@ --- -description: Avoid using null or empty HelpMessage parameter attribute. -ms.date: 06/28/2023 +description: Avoid using null or empty HelpMessage parameter attribute +ms.date: 06/01/2026 ms.topic: reference title: AvoidNullOrEmptyHelpMessageAttribute --- @@ -10,16 +10,16 @@ title: AvoidNullOrEmptyHelpMessageAttribute ## Description -The value of the `HelpMessage` attribute should not be an empty string or a null value as this -causes PowerShell's interpreter to throw an error when executing the function or cmdlet. +This rule detects [HelpMessage][01] attributes that contain null values, empty strings, or no value +assignment. The `HelpMessage` attribute must contain a meaningful, non-empty string value. Omitting +the value altogether causes a parse-time syntax error. -## How - -Specify a value for the `HelpMessage` attribute. +Using an empty string or null value causes PowerShell to raise an error at runtime. Always provide a +descriptive help message that explains the parameter's purpose and expected input to users. ## Example -### Wrong +### Noncompliant ```powershell Function BadFuncEmptyHelpMessageEmpty @@ -56,7 +56,7 @@ Function BadFuncEmptyHelpMessageNoAssignment } ``` -### Correct +### Compliant ```powershell Function GoodFuncHelpMessage @@ -70,3 +70,7 @@ Function GoodFuncHelpMessage $Param } ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters#helpmessage-argument diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidOverwritingBuiltInCmdlets.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidOverwritingBuiltInCmdlets.md index 10e1ad30..a60ef410 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidOverwritingBuiltInCmdlets.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidOverwritingBuiltInCmdlets.md @@ -1,6 +1,6 @@ --- -description: Avoid overwriting built in cmdlets -ms.date: 12/12/2024 +description: Avoid overwriting built-in cmdlets +ms.date: 06/01/2026 ms.topic: reference title: AvoidOverwritingBuiltInCmdlets --- @@ -10,44 +10,78 @@ title: AvoidOverwritingBuiltInCmdlets ## Description -This rule flags cmdlets that are available in a given edition/version of PowerShell on a given -operating system which are overwritten by a function declaration. It works by comparing function -declarations against a set of allowlists that ship with PSScriptAnalyzer. These allowlist files are -used by other PSScriptAnalyzer rules. More information can be found in the documentation for the -[UseCompatibleCmdlets][01] rule. +This rule detects and warns when a script defines a function that uses the name of a built-in cmdlet +available for a target PowerShell version and operating system. Overwriting built-in cmdlet names +can cause confusing behavior because callers might run your function when they expected the platform +cmdlet. -## Configuration +The rule compares function declarations in your script against command allow lists that ship with +PSScriptAnalyzer. The allow lists are also used by other compatibility rules. To learn more, see +[UseCompatibleCmdlets][01]. -To enable the rule to check if your script is compatible on PowerShell Core on Windows, put the -following your settings file. +## Example + +### Noncompliant + +```powershell +function Get-ChildItem { + param( + [string]$Path = '.' + ) + + "Custom listing for: $Path" +} +``` + +### Compliant + +```powershell +function Get-CustomChildItem { + param( + [string]$Path = '.' + ) + + "Custom listing for: $Path" +} +``` + +## Configure rule + +To enable the rule to check if your script is compatible on PowerShell Core on Windows, add the +following lines in your settings file. ```powershell @{ 'Rules' = @{ 'PSAvoidOverwritingBuiltInCmdlets' = @{ - 'PowerShellVersion' = @('core-6.1.0-windows') + 'PowerShellVersion' = @('core-7.0.0-windows') } } } ``` -### Parameters +## Parameters -#### PowerShellVersion +### PowerShellVersion -The parameter `PowerShellVersion` is a list of allowlists that ship with PSScriptAnalyzer. +The `PowerShellVersion` parameter accepts one or more command allow list names that ship with +PSScriptAnalyzer. Set this value to the PowerShell version and platform you want to validate +against. > [!NOTE] -> The default value for `PowerShellVersion` is `core-6.1.0-windows` if PowerShell 6 or -> later is installed, and `desktop-5.1.14393.206-windows` if it's not. +> The default value for `PowerShellVersion` is `core-7.0.0-windows` if PowerShell 7 or later is +installed, and `desktop-5.1.17763.316-windows` if it's not. -Usually, patched versions of PowerShell have the same cmdlet data, therefore only settings of major -and minor versions of PowerShell are supplied. One can also create a custom settings file as well -with the [New-CommandDataFile.ps1][02] script and use it by placing the created `JSON` into the -`Settings` folder of the `PSScriptAnalyzer` module installation folder, then the `PowerShellVersion` -parameter is just its filename (that can also be changed if desired). Note that the `core-6.0.2-*` -files were removed in PSScriptAnalyzer 1.18 since PowerShell 6.0 reached end of life. +Patched PowerShell releases usually share the same cmdlet metadata, so the built-in allow lists are +provided by major and minor version. You can also generate a custom allow list with +[New-CommandDataFile.ps1][02]. To use a custom allow list, place the generated JSON file in the +`Settings` folder of the PSScriptAnalyzer module installation path, then set `PowerShellVersion` to +that filename. + +The `core-6.0.2-*` files were removed in PSScriptAnalyzer 1.18 because PowerShell 6.0 reached end of +life. -[01]: ./UseCompatibleCmdlets.md + +[01]: UseCompatibleCmdlets.md [02]: https://github.com/PowerShell/PSScriptAnalyzer/blob/main/Utils/New-CommandDataFile.ps1 diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidReservedWordsAsFunctionNames.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidReservedWordsAsFunctionNames.md index 046a93be..0c7ac006 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidReservedWordsAsFunctionNames.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidReservedWordsAsFunctionNames.md @@ -1,6 +1,6 @@ --- description: Avoid reserved words as function names -ms.date: 08/31/2025 +ms.date: 06/01/2026 ms.topic: reference title: AvoidReservedWordsAsFunctionNames --- @@ -10,19 +10,15 @@ title: AvoidReservedWordsAsFunctionNames ## Description -Avoid using reserved words as function names. Using reserved words as function names can cause -errors or unexpected behavior in scripts. - -## How to Fix - -Avoid using any of the reserved words as function names. Choose a different name that's not a -reserved word. +This rule detects function names that use PowerShell reserved words. Using reserved words as +function names causes errors or unexpected behavior in PowerShell scripts. Choose function names +that don't conflict with any PowerShell reserved words. See [about_Reserved_Words][01] for a list of reserved words in PowerShell. ## Example -### Wrong +### Noncompliant ```powershell # Function is a reserved word @@ -31,7 +27,7 @@ function function { } ``` -### Correct +### Compliant ```powershell # myFunction is not a reserved word @@ -41,4 +37,5 @@ function myFunction { ``` + [01]: /powershell/module/microsoft.powershell.core/about/about_reserved_words From ede4f44dc4185f48d2cdc55f0110259bbe87aa26 Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Thu, 4 Jun 2026 10:47:19 -0400 Subject: [PATCH 3/4] [Freshness] PSScriptAnalyzer Article Updates - Batch 3 (#404) * Freshness * Applied feedback * Applied feedback --- .../Rules/AvoidSemicolonsAsLineTerminators.md | 26 +++++----- .../Rules/AvoidShouldContinueWithoutForce.md | 26 ++++++---- .../Rules/AvoidTrailingWhitespace.md | 48 +++++++++++++++++-- ...voidUsingAllowUnencryptedAuthentication.md | 26 +++++----- .../Rules/AvoidUsingBrokenHashAlgorithms.md | 33 ++++--------- 5 files changed, 100 insertions(+), 59 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidSemicolonsAsLineTerminators.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidSemicolonsAsLineTerminators.md index 4716238c..e9d757fe 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidSemicolonsAsLineTerminators.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidSemicolonsAsLineTerminators.md @@ -1,6 +1,6 @@ --- description: Avoid semicolons as line terminators -ms.date: 06/28/2023 +ms.date: 06/01/2026 ms.topic: reference title: AvoidSemicolonsAsLineTerminators --- @@ -10,14 +10,17 @@ title: AvoidSemicolonsAsLineTerminators ## Description -Lines should not end with a semicolon. +This rule detects semicolons used as line terminators at the end of statements. In PowerShell, +line-ending semicolons are redundant and detract from code readability. Although semicolons serve as +statement separators on a single line, using them as line terminators is discouraged. Avoid using +semicolons at the end of lines. -> [!NOTE] -> This rule is not enabled by default. The user needs to enable it through settings. +This rule promotes cleaner, more maintainable code by removing unnecessary semicolons. This rule +isn't enabled by default. ## Example -### Wrong +### Noncompliant ```powershell Install-Module -Name PSScriptAnalyzer; $a = 1 + $b; @@ -28,7 +31,7 @@ Install-Module -Name PSScriptAnalyzer; $a = 1 + $b ``` -### Correct +### Compliant ```powershell Install-Module -Name PSScriptAnalyzer; $a = 1 + $b @@ -43,14 +46,15 @@ $a = 1 + $b ```powershell Rules = @{ - PSAvoidSemicolonsAsLineTerminators = @{ - Enable = $true + PSAvoidSemicolonsAsLineTerminators = @{ + Enable = $true } } ``` -### Parameters +## Parameters -#### Enable: bool (Default value is `$false`) +### Enable -Enable or disable the rule during ScriptAnalyzer invocation. +This parameter controls whether ScriptAnalyzer checks the code against this rule. It accepts a +boolean value. To enable this rule, set this parameter to `$true`. The default value is `$false`. diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidShouldContinueWithoutForce.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidShouldContinueWithoutForce.md index 189989a8..8a9ce7c3 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidShouldContinueWithoutForce.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidShouldContinueWithoutForce.md @@ -1,6 +1,6 @@ --- -description: Avoid Using ShouldContinue Without Boolean Force Parameter -ms.date: 06/28/2023 +description: Avoid using ShouldContinue without boolean Force parameter +ms.date: 06/01/2026 ms.topic: reference title: AvoidShouldContinueWithoutForce --- @@ -10,18 +10,19 @@ title: AvoidShouldContinueWithoutForce ## Description -Functions that use ShouldContinue should have a boolean force parameter to allow user to bypass it. +This rule detects functions that use `ShouldContinue` without a boolean `Force` parameter. Functions +that use `ShouldContinue` should have a boolean `Force` parameter to allow users to bypass the +confirmation prompt. -You can get more details by running `Get-Help about_Functions_CmdletBindingAttribute` and -`Get-Help about_Functions_Advanced_Methods` command in PowerShell. +When using `ShouldContinue` in advanced functions, call it after the +`ShouldProcess` method returns `$true`. -## How - -Call the `ShouldContinue` method in advanced functions when `ShouldProcess` method returns `$true`. +To learn more, see [about_Functions_CmdletBindingAttribute][01] and +[about_Functions_Advanced_Methods][02]. ## Example -### Wrong +### Noncompliant ```powershell Function Test-ShouldContinue @@ -39,7 +40,7 @@ Function Test-ShouldContinue } ``` -### Correct +### Compliant ```powershell Function Test-ShouldContinue @@ -57,3 +58,8 @@ Function Test-ShouldContinue } } ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute +[02]: /powershell/module/microsoft.powershell.core/about/about_functions_advanced_methods diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidTrailingWhitespace.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidTrailingWhitespace.md index 416948c3..58e7bc84 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidTrailingWhitespace.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidTrailingWhitespace.md @@ -1,6 +1,6 @@ --- description: Avoid trailing whitespace -ms.date: 06/28/2023 +ms.date: 06/01/2026 ms.topic: reference title: AvoidTrailingWhitespace --- @@ -10,5 +10,47 @@ title: AvoidTrailingWhitespace ## Description -Lines should not end with whitespace characters. This can cause problems with the line-continuation -backtick, and also clutters up future commits to source control. +This rule detects lines that end with trailing whitespace characters. Lines shouldn't end with +trailing whitespace characters. Trailing whitespace makes diffs harder to review and can introduce +subtle problems when line continuation uses a backtick (`), because the backtick must be the last +character on the line. + +Keeping lines free of trailing whitespace improves readability and helps keep source control history +clean. + +To learn more, see [about_Parsing][01]. + +## Example + +### Noncompliant + +```powershell +# The next line ends with a trailing space after the backtick. +Get-Process ` +| Where-Object { $_.CPU -gt 100 } +``` + +When you run this script, PowerShell throws a parser error because the trailing space prevents line +continuation. For example: + +```output +PS C:\WINDOWS\system32> Get-Process ` +| Where-Object { $_.CPU -gt 100 } +At line:2 char:1 ++ | Where-Object { $_.CPU -gt 100 } ++ ~ +An empty pipe element is not allowed. + + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + + FullyQualifiedErrorId : EmptyPipeElement +``` + +### Compliant + +```powershell +Get-Process ` +| Where-Object { $_.CPU -gt 100 } +``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_parsing diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingAllowUnencryptedAuthentication.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingAllowUnencryptedAuthentication.md index 20451e66..7b041775 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingAllowUnencryptedAuthentication.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingAllowUnencryptedAuthentication.md @@ -1,6 +1,6 @@ --- description: Avoid sending credentials and secrets over unencrypted connections -ms.date: 02/28/2024 +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingAllowUnencryptedAuthentication --- @@ -10,26 +10,30 @@ title: AvoidUsingAllowUnencryptedAuthentication ## Description -Avoid using the **AllowUnencryptedAuthentication** parameter of `Invoke-WebRequest` and -`Invoke-RestMethod`. When using this parameter, the cmdlets send credentials and secrets over -unencrypted connections. This should be avoided except for compatibility with legacy systems. +This rule detects the **AllowUnencryptedAuthentication** parameter used with `Invoke-WebRequest` and +`Invoke-RestMethod` cmdlets. When **AllowUnencryptedAuthentication** is used, it permits credentials +and secrets to be transmitted over unencrypted connections, creating a security risk. -For more details, see [Invoke-RestMethod](xref:Microsoft.PowerShell.Utility.Invoke-RestMethod). +Avoid using this parameter unless you must maintain compatibility with legacy systems that require +unencrypted authentication. -## How +To learn more, see [Invoke-WebRequest][01] and [Invoke-RestMethod][02]. -Avoid using the **AllowUnencryptedAuthentication** parameter. +## Example -## Example 1 - -### Wrong +### Noncompliant ```powershell Invoke-WebRequest foo -AllowUnencryptedAuthentication ``` -### Correct +### Compliant ```powershell Invoke-WebRequest foo ``` + + + +[01]: /powershell/module/microsoft.powershell.utility/invoke-webrequest +[02]: /powershell/module/microsoft.powershell.utility/invoke-restmethod diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingBrokenHashAlgorithms.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingBrokenHashAlgorithms.md index 32bb464a..8371c93a 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingBrokenHashAlgorithms.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingBrokenHashAlgorithms.md @@ -1,6 +1,6 @@ --- description: Avoid using broken hash algorithms -ms.date: 06/28/2023 +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingBrokenHashAlgorithms --- @@ -10,38 +10,23 @@ title: AvoidUsingBrokenHashAlgorithms ## Description -Avoid using the broken algorithms MD5 or SHA-1. +This rule detects the use of cryptographically broken hash algorithms `MD5` and `SHA-1`. Avoid using +hash algorithms `MD5` and `SHA-1`. These algorithms are vulnerable to collision attacks and are no +longer considered secure for cryptographic purposes. -## How +Replace `MD5` and `SHA-1` with secure alternatives such as `SHA256`, `SHA384`, or `SHA512`. Use +broken algorithms only when strictly necessary for backwards compatibility with legacy systems. -Replace broken algorithms with secure alternatives. MD5 and SHA-1 should be replaced with SHA256, -SHA384, SHA512, or other safer algorithms when possible, with MD5 and SHA-1 only being utilized by -necessity for backwards compatibility. +## Example -## Example 1 - -### Wrong +### Noncompliant ```powershell Get-FileHash foo.txt -Algorithm MD5 ``` -### Correct +### Compliant ```powershell Get-FileHash foo.txt -Algorithm SHA256 ``` - -## Example 2 - -### Wrong - -```powershell -Get-FileHash foo.txt -Algorithm SHA1 -``` - -### Correct - -```powershell -Get-FileHash foo.txt -``` From d98b784dd551493fb377448643a911184bdaf49f Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Thu, 4 Jun 2026 13:27:41 -0400 Subject: [PATCH 4/4] [Freshness] PSScriptAnalyzer Article Updates - Batch 4 (#405) * Freshness * Fix validation * Freshness * Applied feedback * Applied feedback --- .../Rules/AvoidUsingCmdletAliases.md | 61 +++++++++---------- .../Rules/AvoidUsingComputerNameHardcoded.md | 43 ++++--------- ...UsingConvertToSecureStringWithPlainText.md | 28 +++++---- .../AvoidUsingDeprecatedManifestFields.md | 20 +++--- ...AvoidUsingDoubleQuotesForConstantString.md | 27 ++++---- 5 files changed, 81 insertions(+), 98 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingCmdletAliases.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingCmdletAliases.md index 9a33149a..b92aa878 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingCmdletAliases.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingCmdletAliases.md @@ -1,6 +1,6 @@ --- -description: Avoid Using Cmdlet Aliases or omitting the 'Get-' prefix. -ms.date: 06/28/2023 +description: Avoid using cmdlet aliases or omitting the Get- prefix +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingCmdletAliases --- @@ -10,35 +10,44 @@ title: AvoidUsingCmdletAliases ## Description -An alias is an alternate name or nickname for a cmdlet or for a command element, such as a function, -script, file, or executable file. You can use the alias instead of the command name in any -PowerShell commands. +This rule detects the use of cmdlet aliases and omission of the `Get-` prefix in implicit alias +scenarios. An alias is an alternate name or nickname for a cmdlet or command element, such as a +function, script, file, or executable file. While you can use aliases instead of the full command +name, doing so reduces code readability and maintainability. -There are also implicit aliases. When PowerShell cannot find the cmdlet name, it will try to append -`Get-` to the command as a last resort. Therefore using the command `verb` will execute `Get-Verb`. +PowerShell also supports implicit aliases. When a cmdlet name isn't found, PowerShell appends +`Get-` to the command as a fallback. For example, typing `verb` executes `Get-Verb`. -Every PowerShell author learns the actual command names, but different authors learn and use -different aliases. Aliases can make code difficult to read, understand and impact availability. +Aliases create inconsistency across codebases because different authors learn and use different +aliases. Aliases can potentially make code difficult to read and understand in collaborative +environments. It can also cause issues with script portability and availability. -Using the full command name makes it easier to maintain your scripts in the the future. +Using full cmdlet names improves code clarity, makes scripts easier to maintain, and enables proper +syntax highlighting in code editors and platforms like GitHub and Visual Studio Code. Always use the +full cmdlet name instead of aliases. -Using the full command names also allows for syntax highlighting in sites and applications like -GitHub and Visual Studio Code. +## Example + +### Noncompliant + +```powershell +gps | Where-Object {$_.WorkingSet -gt 20000000} +``` -## How to Fix +### Compliant -Use the full cmdlet name and not an alias. +```powershell +Get-Process | Where-Object {$_.WorkingSet -gt 20000000} +``` -## Alias Allowlist +## Configure rule -To prevent `PSScriptAnalyzer` from flagging your preferred aliases, create an allowlist of the +To prevent `PSScriptAnalyzer` from flagging your preferred aliases, create an allow list of the aliases in your settings file and point `PSScriptAnalyzer` to use the settings file. For example, to disable `PSScriptAnalyzer` from flagging `cd`, which is an alias of `Set-Location`, set the settings file content to the following. ```powershell -# PSScriptAnalyzerSettings.psd1 - @{ 'Rules' = @{ 'PSAvoidUsingCmdletAliases' = @{ @@ -46,18 +55,4 @@ file content to the following. } } } -``` - -## Example - -### Wrong - -```powershell -gps | Where-Object {$_.WorkingSet -gt 20000000} -``` - -### Correct - -```powershell -Get-Process | Where-Object {$_.WorkingSet -gt 20000000} -``` +``` \ No newline at end of file diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingComputerNameHardcoded.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingComputerNameHardcoded.md index 83a60c95..73ac31f2 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingComputerNameHardcoded.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingComputerNameHardcoded.md @@ -1,6 +1,6 @@ --- -description: Avoid Using ComputerName Hardcoded -ms.date: 06/28/2023 +description: Avoid using hardcoded computer names +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingComputerNameHardcoded --- @@ -10,25 +10,26 @@ title: AvoidUsingComputerNameHardcoded ## Description -The names of computers should never be hard coded as this will expose sensitive information. The -`ComputerName` parameter should never have a hard coded value. +This rule detects hard-coded computer names in the `ComputerName` parameter of cmdlets. Hard-coded +computer names can expose sensitive information and reduce script portability. The `ComputerName` +parameter should always be parameterized or dynamically assigned to ensure scripts are flexible and +secure. -## How +Use parameters, environment variables, or dynamic values instead of hard-coded computer +names. -Remove hard coded computer names. +## Example -## Example 1 - -### Wrong +### Noncompliant ```powershell Function Invoke-MyRemoteCommand () { - Invoke-Command -Port 343 -ComputerName hardcoderemotehostname + Invoke-Command -Port 343 -ComputerName HardcodedRemoteHostname } ``` -### Correct +### Compliant ```powershell Function Invoke-MyCommand ($ComputerName) @@ -36,23 +37,3 @@ Function Invoke-MyCommand ($ComputerName) Invoke-Command -Port 343 -ComputerName $ComputerName } ``` - -## Example 2 - -### Wrong - -```powershell -Function Invoke-MyLocalCommand () -{ - Invoke-Command -Port 343 -ComputerName hardcodelocalhostname -} -``` - -### Correct - -```powershell -Function Invoke-MyLocalCommand () -{ - Invoke-Command -Port 343 -ComputerName $env:COMPUTERNAME -} -``` diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingConvertToSecureStringWithPlainText.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingConvertToSecureStringWithPlainText.md index d25fce12..73756712 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingConvertToSecureStringWithPlainText.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingConvertToSecureStringWithPlainText.md @@ -1,6 +1,6 @@ --- description: Avoid Using SecureString With Plain Text -ms.date: 01/28/2025 +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingConvertToSecureStringWithPlainText --- @@ -10,31 +10,35 @@ title: AvoidUsingConvertToSecureStringWithPlainText ## Description -The use of the `AsPlainText` parameter with the `ConvertTo-SecureString` command can expose secure -information. +This rule detects the use of the `AsPlainText` parameter with the `ConvertTo-SecureString` command, +which bypasses encryption and exposes sensitive information in memory as plain text, defeating the +purpose of [SecureString][01]. -## How - -Use a standard encrypted variable to perform any SecureString conversions. +Instead, retrieve secure credentials through encrypted channels or use secure input methods like +`Read-Host -AsSecureString` to ensure sensitive data remains encrypted throughout its lifecycle. ## Recommendations -If you do need an ability to retrieve the password from somewhere without prompting the user, -consider using the -[SecretStore](https://www.powershellgallery.com/packages/Microsoft.PowerShell.SecretStore) -module from the PowerShell Gallery. +If you need to retrieve passwords programmatically without user interaction, consider using the +[SecretStore][02] module from the PowerShell Gallery, which provides encrypted credential storage +and retrieval. ## Example -### Wrong +### Noncompliant ```powershell $UserInput = Read-Host 'Please enter your secure code' $EncryptedInput = ConvertTo-SecureString -String $UserInput -AsPlainText -Force ``` -### Correct +### Compliant ```powershell $SecureUserInput = Read-Host 'Please enter your secure code' -AsSecureString ``` + + + +[01]: /dotnet/api/system.security.securestring +[02]: https://www.powershellgallery.com/packages/Microsoft.PowerShell.SecretStore diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDeprecatedManifestFields.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDeprecatedManifestFields.md index 802304df..fd83bea2 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDeprecatedManifestFields.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDeprecatedManifestFields.md @@ -1,6 +1,6 @@ --- -description: Avoid Using Deprecated Manifest Fields -ms.date: 06/28/2023 +description: Avoid using deprecated manifest fields +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingDeprecatedManifestFields --- @@ -10,17 +10,17 @@ title: AvoidUsingDeprecatedManifestFields ## Description -In PowerShell 5.0, a number of fields in module manifest files (`.psd1`) have been changed. +This rule detects the usage of deprecated manifest fields in module manifest files (`.psd1`) that +should be replaced with their modern equivalents. PowerShell 5.0 deprecated several fields in module +manifest files (`.psd1`) in favor of new alternatives. -The field `ModuleToProcess` has been replaced with the `RootModule` field. - -## How - -Replace `ModuleToProcess` with `RootModule` in the module manifest. +The `ModuleToProcess` field, which was used to specify the module script file to load, is replaced +with the `RootModule` field. The `RootModule` field provides the same functionality and is the +recommended approach for new modules. ## Example -### Wrong +### Noncompliant ```powershell ModuleToProcess ='psscriptanalyzer' @@ -28,7 +28,7 @@ ModuleToProcess ='psscriptanalyzer' ModuleVersion = '1.0' ``` -### Correct +### Compliant ```powershell RootModule ='psscriptanalyzer' diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDoubleQuotesForConstantString.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDoubleQuotesForConstantString.md index 19c83fad..bc51d463 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDoubleQuotesForConstantString.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidUsingDoubleQuotesForConstantString.md @@ -1,6 +1,6 @@ --- -description: Avoid using double quotes if the string is constant. -ms.date: 06/28/2023 +description: Avoid using double quotes if the string is constant +ms.date: 06/01/2026 ms.topic: reference title: AvoidUsingDoubleQuotesForConstantString --- @@ -10,26 +10,29 @@ title: AvoidUsingDoubleQuotesForConstantString ## Description -Single quotes should be used when the value of a string is constant. A constant string doesn't -contain variables or expressions intended to insert values into the string, such as -`"$PID-$(hostname)"`). +This rule detects static strings enclosed with double quotes (`""`) with text that doesn't +contain variables, expressions, or special characters that require escaping. -This makes the intent clearer that the string is a constant and makes it easier to use some special -characters such as `$` within that string expression without needing to escape them. +Enclose text with single quotes (`''`) when the value of a string is constant. A constant +string doesn't contain variables or expressions intended to insert values into the string, such as +`"$PID-$(hostname)"`. Using single quotes makes the intent clearer that the string is constant and +allows you to use special characters such as `$` without needing to escape them. -There are exceptions to that when double quoted strings are more readable. For example, when the -string value itself must contain a single quote or other special characters, such as newline -(`` "`n" ``), are already being escaped. The rule does not warn in these cases. +However, there are exceptions where this rule doesn't flag violations: + +- Double-quoted strings are preferred when the string contains single quotes +- Embedded escape sequences like newline (``"`n"``) +- Other special characters that require escaping ## Example -### Wrong +### Noncompliant ```powershell $constantValue = "I Love PowerShell" ``` -### Correct +### Compliant ```powershell $constantValue = 'I Love PowerShell'