From cb320b76515023202a1c8e5e9394b26a30cd947a Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Mon, 15 Jun 2026 09:20:07 -0400 Subject: [PATCH 1/3] [Freshness] PSScriptAnalyzer Article Updates - Batch 14 (#417) * Freshness * Freshness * Applied feedback --- .../UseSingleValueFromPipelineParameter.md | 31 ++++----- .../Rules/UseSingularNouns.md | 68 ++++++++++--------- .../Rules/UseSupportsShouldProcess.md | 18 ++--- .../Rules/UseToExportFieldsInManifest.md | 44 +++--------- .../Rules/UseUTF8EncodingForHelpFile.md | 58 ++++++++++++---- .../UseUsingScopeModifierInNewRunspaces.md | 55 ++++----------- 6 files changed, 128 insertions(+), 146 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingleValueFromPipelineParameter.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingleValueFromPipelineParameter.md index 92c350eb..b59fee9d 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingleValueFromPipelineParameter.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingleValueFromPipelineParameter.md @@ -1,6 +1,6 @@ --- -description: Use at most a single ValueFromPipeline parameter per parameter set. -ms.date: 03/20/2026 +description: Use a single ValueFromPipeline parameter per parameter set +ms.date: 06/11/2026 ms.topic: reference title: UseSingleValueFromPipelineParameter --- @@ -10,19 +10,17 @@ title: UseSingleValueFromPipelineParameter ## Description -Parameter sets should have at most one parameter marked as `ValueFromPipeline = true`. +This rule detects functions where multiple parameters within the same parameter set are marked as +accepting pipeline input by value. Parameter sets should have at most one parameter with +`ValueFromPipeline = true`. -This rule identifies functions where multiple parameters within the same parameter set have -`ValueFromPipeline` set to `true` (either explicitly or implicitly). - -## How - -Ensure that only one parameter per parameter set accepts pipeline input by value. If you need -multiple parameters to accept different types of pipeline input, use separate parameter sets. +When you need multiple parameters to accept different types of pipeline input, use separate +parameter sets instead. Each parameter set can have its own single `ValueFromPipeline` parameter, +but you can't have more than one within the same parameter set. ## Example -### Wrong +### Noncompliant ```powershell function Process-Data { @@ -41,8 +39,7 @@ function Process-Data { } ``` - -### Correct +### Compliant ```powershell function Process-Data { @@ -91,9 +88,9 @@ For the default parameter set, use `'default'` as the suppression target: ## Notes - This rule applies to both explicit `ValueFromPipeline = $true` and implicit `ValueFromPipeline` - (which is the same as using `= $true`) -- Parameters with `ValueFromPipeline=$false` are not flagged by this rule + (which is the same as using `= $true`). +- This rule doesn't flag parameters with `ValueFromPipeline = $false`. - The rule correctly handles the default parameter set (`__AllParameterSets`) and named parameter - sets + sets. - Different parameter sets can each have their own single `ValueFromPipeline` parameter without - triggering this rule + triggering this rule. diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingularNouns.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingularNouns.md index 3997c069..172503c4 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingularNouns.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSingularNouns.md @@ -1,6 +1,6 @@ --- -description: Cmdlet Singular Noun -ms.date: 03/27/2024 +description: Use single cmdlet nouns +ms.date: 06/11/2026 ms.topic: reference title: UseSingularNouns --- @@ -10,8 +10,14 @@ title: UseSingularNouns ## Description -PowerShell team best practices state cmdlets should use singular nouns and not plurals. Suppression -allows you to suppress the rule for specific function names. For example: +This rule detects cmdlet names that use plural nouns instead of singular nouns. + +PowerShell best practices require that cmdlets use singular nouns, not plurals. You can use the +`NounAllowList` parameter to exclude specific nouns from this rule, or suppress the rule for +individual functions using `SuppressMessageAttribute`. If a violation is found, change the plural +noun to its singular form. + +For example: ``` function Get-Elements { @@ -20,35 +26,9 @@ function Get-Elements { } ``` -## Configuration - -```powershell -Rules = @{ - PSUseSingularNouns = @{ - Enable = $true - NounAllowList = 'Data', 'Windows', 'Foos' - } -} -``` - -### Parameters - -- `Enable`: `bool` (Default value is `$true`) - - Enable or disable the rule during ScriptAnalyzer invocation. - -- `NounAllowList`: `string[]` (Default value is `{'Data', 'Windows'}`) - - Commands to be excluded from this rule. `Data` and `Windows` are common false positives and are - excluded by default. - -## How - -Change plurals to singular. - ## Example -### Wrong +### Noncompliant ```powershell function Get-Files @@ -57,7 +37,7 @@ function Get-Files } ``` -### Correct +### Compliant ```powershell function Get-File @@ -65,3 +45,27 @@ function Get-File ... } ``` + +## Configuration + +```powershell +Rules = @{ + PSUseSingularNouns = @{ + Enable = $true + NounAllowList = 'Data', 'Windows', 'Foos' + } +} +``` + +## Parameters + +### Enable + +This parameter controls whether ScriptAnalyzer checks the code against this rule. It accepts a +boolean value. To disable this rule, set this parameter to `$false`. The default value is `$true`. + +### NounAllowList + +This parameter specifies which noun commands to exclude from this rule. It accepts a string value. +Both `Data` and `Windows` are common false positives and excluded by default. Default values are +`'Data'` and `'Windows'`. diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSupportsShouldProcess.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSupportsShouldProcess.md index 904ad077..24ce3d80 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSupportsShouldProcess.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseSupportsShouldProcess.md @@ -1,6 +1,6 @@ --- description: Use SupportsShouldProcess -ms.date: 06/28/2023 +ms.date: 06/11/2026 ms.topic: reference title: UseSupportsShouldProcess --- @@ -10,15 +10,17 @@ title: UseSupportsShouldProcess ## Description -This rule discourages manual declaration of `WhatIf` and `Confirm` parameters in a function/cmdlet. -These parameters are, however, provided automatically when a function declares a `CmdletBinding` -attribute with `SupportsShouldProcess` as its named argument. Using `SupportsShouldProcess` not only -provides these parameters but also some generic functionality that allows the function/cmdlet -authors to provide the desired interactive experience while using the cmdlet. +This rule detects manual declarations of `WhatIf` and `Confirm` parameters in functions and cmdlets. +Rather than manually declaring these parameters, you should use the `CmdletBinding` attribute with +`SupportsShouldProcess` as a named argument. + +This approach automatically provides both parameters along with built-in functionality that gives +you and your users a consistent interactive experience. Using `SupportsShouldProcess` is more +maintainable and provides standard behavior without extra code. ## Example -### Wrong +### Noncompliant ```powershell function foo { @@ -30,7 +32,7 @@ function foo { } ``` -### Correct +### Compliant ```powershell function foo { diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseToExportFieldsInManifest.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseToExportFieldsInManifest.md index 5faaf9d1..1d5038c2 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseToExportFieldsInManifest.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseToExportFieldsInManifest.md @@ -1,6 +1,6 @@ --- -description: Use the *ToExport module manifest fields. -ms.date: 06/28/2023 +description: Use the *ToExport module manifest fields +ms.date: 06/11/2026 ms.topic: reference title: UseToExportFieldsInManifest --- @@ -10,50 +10,28 @@ title: UseToExportFieldsInManifest ## Description -To improve the performance of module auto-discovery, module manifests should not use wildcards -(`'*'`) or null (`$null`) in the following entries: +This rule detects when module manifests use wildcards (`'*'`) or null (`$null`) in export fields. To +improve module autodiscovery performance, module manifests shouldn't use wildcards or null in the +following entries: - `AliasesToExport` - `CmdletsToExport` - `FunctionsToExport` - `VariablesToExport` -Using wildcards or null has causes PowerShell to perform expensive work to analyze a module during -module auto-discovery. +When you use wildcards or null, PowerShell performs expensive analysis of your module during +autodiscovery. Instead, use an explicit list of items to export. -## How +## Example -Use an explicit list in the entries. - -## Example 1 - -Suppose there are no functions in your module to export. Then, - -### Wrong +### Noncompliant ```powershell FunctionsToExport = $null ``` -### Correct - -```powershell -FunctionToExport = @() -``` - -## Example 2 - -Suppose there are only two functions in your module, `Get-Foo` and `Set-Foo` that you want to -export. Then, - -### Wrong - -```powershell -FunctionsToExport = '*' -``` - -### Correct +### Compliant ```powershell -FunctionToExport = @(Get-Foo, Set-Foo) +FunctionsToExport = @() ``` diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUTF8EncodingForHelpFile.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUTF8EncodingForHelpFile.md index e34c35ec..b5063d63 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUTF8EncodingForHelpFile.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUTF8EncodingForHelpFile.md @@ -1,6 +1,6 @@ --- -description: Use UTF8 Encoding For Help File -ms.date: 01/07/2025 +description: Use UTF8 encoding for help file +ms.date: 06/11/2026 ms.topic: reference title: UseUTF8EncodingForHelpFile --- @@ -10,24 +10,52 @@ title: UseUTF8EncodingForHelpFile ## Description -Check that an `about_` help file uses UTF-8 encoding. The filename must start with `about_` and end -with `.help.txt`. The rule uses the **CurrentEncoding** property of the **StreamReader** class to -determine the encoding of the file. +This rule detects when an `about_` help file doesn't use UTF-8 encoding. The rule verifies that help +files starting with `about_` and ending with `.help.txt` are saved in UTF-8 encoding. It uses the +**CurrentEncoding** property of the **StreamReader** class to check the file's encoding. -## How +To ensure your help files use the correct encoding, follow these guidelines: -For PowerShell commands that write to files, ensure that you set the encoding parameter to `utf8`, -`utf8BOM`, or `utf8NoBOM`. +- When using PowerShell commands to write to files, set the encoding parameter to `utf8`, `utf8BOM`, + or `utf8NoBOM`. +- When creating or editing help files in a text editor, configure it to save files in UTF-8 format. + Consult your editor's documentation for instructions on setting the file encoding. -When you create a help file using a text editor, ensure that the editor is configured to save the -file in a UTF8 format. Consult the documentation for your text editor for instructions on how to -save files with a specific encoding. +## Example -## Further reading +### Noncompliant + +```powershell +$helpText = @' +TOPIC + about_Contoso + +SHORT DESCRIPTION + Describes Contoso commands. +'@ + +$helpText | Set-Content -Path "about_Contoso.help.txt" -Encoding Unicode +``` + +### Compliant + +```powershell +$helpText = @' +TOPIC + about_Contoso + +SHORT DESCRIPTION + Describes Contoso commands. +'@ + +$helpText | Set-Content -Path "about_Contoso.help.txt" -Encoding utf8NoBOM +``` + +## See also For more information, see the following articles: -- [System.IO.StreamReader](xref:System.IO.StreamReader.CurrentEncoding%2A) +- [System.IO.StreamReader](/dotnet/api/system.io.streamreader.currentencoding) - [about_Character_Encoding](/powershell/module/microsoft.powershell.core/about/about_character_encoding) -- [Set-Content](xref:Microsoft.PowerShell.Management.Set-Content) -- [Understanding file encoding in VS Code and PowerShell](/powershell/scripting/dev-cross-plat/vscode/understanding-file-encoding) +- [Set-Content](/powershell/module/microsoft.powershell.management/set-content) +- [Understanding file encoding in Visual Studio Code and PowerShell](/powershell/scripting/dev-cross-plat/vscode/understanding-file-encoding) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUsingScopeModifierInNewRunspaces.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUsingScopeModifierInNewRunspaces.md index bde0f667..17177f79 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUsingScopeModifierInNewRunspaces.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUsingScopeModifierInNewRunspaces.md @@ -1,6 +1,6 @@ --- -description: Use 'Using:' scope modifier in RunSpace ScriptBlocks -ms.date: 06/28/2023 +description: Use the '$using:' scope modifier in runspace scriptblocks +ms.date: 06/11/2026 ms.topic: reference title: UseUsingScopeModifierInNewRunspaces --- @@ -10,61 +10,34 @@ title: UseUsingScopeModifierInNewRunspaces ## Description -If a scriptblock is intended to be run in a new runspace, variables inside it should use the -`$using:` scope modifier, or be initialized within the scriptblock. This applies to: +This rule detects when scriptblocks running in new runspaces reference parent scope variables +without the `$using:` scope modifier. When a scriptblock is intended to run in a new runspace, it +can't directly access variables from the parent scope. + +You must either use the `$using:` scope modifier to explicitly reference a parent scope variable, or +initialize the variable within the scriptblock itself. This rule applies to: - `Invoke-Command`- Only with the **ComputerName** or **Session** parameter. -- `Workflow { InlineScript {} }` +- `Workflow { InlineScript {} }` (supported only in Windows PowerShell 5.1 and earlier; not + available in PowerShell 7+) - `Foreach-Object` - Only with the **Parallel** parameter - `Start-Job` - `Start-ThreadJob` -- The `Script` resource in DSC configurations, specifically for the `GetScript`, `TestScript` and - `SetScript` properties. - -## How to Fix - -Within the ScriptBlock, instead of just using a variable from the parent scope, you have to add the -`using:` scope modifier to it. +- The `Script` resource in Desired State Configuration (DSC) configurations, specifically for the + `GetScript`, `SetScript`, and `TestScript` properties. ## Example -### Wrong +### Noncompliant ```powershell $var = 'foo' 1..2 | ForEach-Object -Parallel { $var } ``` -### Correct +### Compliant ```powershell $var = 'foo' 1..2 | ForEach-Object -Parallel { $using:var } ``` - -## More correct examples - -```powershell -$bar = 'bar' -Invoke-Command -ComputerName 'foo' -ScriptBlock { $using:bar } -``` - -```powershell -$bar = 'bar' -$s = New-PSSession -ComputerName 'foo' -Invoke-Command -Session $s -ScriptBlock { $using:bar } -``` - -```powershell -# Remark: Workflow is supported on Windows PowerShell only -Workflow { - $foo = 'foo' - InlineScript { $using:foo } -} -``` - -```powershell -$foo = 'foo' -Start-ThreadJob -ScriptBlock { $using:foo } -Start-Job -ScriptBlock {$using:foo } -``` From 5c33d71ff509538dae913bd33e90a00e85eb200e Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Mon, 15 Jun 2026 09:21:38 -0400 Subject: [PATCH 2/3] [Freshness] PSScriptAnalyzer Article Updates - Batch 15 (#418) * Freshness * Applied feedback --- .../UseLiteralInitializerForHashtable.md | 28 +++++---------- .../Rules/UseOutputTypeCorrectly.md | 25 +++++++------ .../Rules/UsePSCredentialType.md | 18 +++++----- .../UseProcessBlockForPipelineCommand.md | 34 +++++------------- ...eShouldProcessForStateChangingFunctions.md | 36 ++++++++++--------- 5 files changed, 59 insertions(+), 82 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseLiteralInitializerForHashtable.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseLiteralInitializerForHashtable.md index 16f9a2f9..584b96af 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseLiteralInitializerForHashtable.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseLiteralInitializerForHashtable.md @@ -1,6 +1,6 @@ --- description: Create hashtables with literal initializers -ms.date: 06/28/2023 +ms.date: 06/11/2026 ms.topic: reference title: UseLiteralInitializerForHashtable --- @@ -10,33 +10,23 @@ title: UseLiteralInitializerForHashtable ## Description -Creating a hashtable using `[hashtable]::new()` or `New-Object -TypeName hashtable` without passing -a `IEqualityComparer` object to the constructor creates a hashtable where the keys are looked-up in -a case-sensitive manner. However, PowerShell is case-insensitive in nature and it is best to create -hashtables with case-insensitive key look-up. +This rule detects hashtables created using the `[hashtable]::new()` method or the `New-Object +-TypeName hashtable` cmdlet without passing an `IEqualityComparer` object. When you create a +hashtable using `[hashtable]::new()` or `New-Object -TypeName hashtable`, the keys are looked up in +a case-sensitive manner by default. -This rule is intended to warn the author of the case-sensitive nature of the hashtable when created -using the `new` method or the `New-Object` cmdlet. - -## How to Fix - -Create the hashtable using a literal hashtable expression. +However, PowerShell is case-insensitive in nature, and hashtables should maintain this behavior. To +ensure consistent case-insensitive key lookup, use literal hashtable expressions instead. ## Example -### Wrong +### Noncompliant ```powershell $hashtable = [hashtable]::new() ``` -### Wrong - -```powershell -$hashtable = New-Object -TypeName hashtable -``` - -### Correct +### Compliant ```powershell $hashtable = @{} diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseOutputTypeCorrectly.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseOutputTypeCorrectly.md index 733425fd..99141633 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseOutputTypeCorrectly.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseOutputTypeCorrectly.md @@ -1,6 +1,6 @@ --- -description: Use OutputType Correctly -ms.date: 06/28/2023 +description: Use the OutputType attribute correctly +ms.date: 06/11/2026 ms.topic: reference title: UseOutputTypeCorrectly --- @@ -10,18 +10,17 @@ title: UseOutputTypeCorrectly ## Description -A command should return the same type as declared in `OutputType`. +This rule detects when a function or script returns a different type than what is declared in the +`OutputType` attribute. A function should return values that match the types specified in its +`OutputType` attribute. -You can get more details by running `Get-Help about_Functions_OutputTypeAttribute` command in -PowerShell. - -## How - -Specify that the OutputType attribute lists and the types returned in the cmdlet match. +The `OutputType` attribute documents what type of output a function produces, and the actual return +values should comply with this declaration. To learn more, see +[about_Functions_OutputTypeAttribute][01]. ## Example -### Wrong +### Noncompliant ```powershell function Get-Foo @@ -34,7 +33,7 @@ function Get-Foo } ``` -### Correct +### Compliant ```powershell function Get-Foo @@ -47,3 +46,7 @@ function Get-Foo return 'four' } ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_functions_outputtypeattribute diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UsePSCredentialType.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UsePSCredentialType.md index c962762e..55197630 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UsePSCredentialType.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UsePSCredentialType.md @@ -1,6 +1,6 @@ --- -description: Use PSCredential type. -ms.date: 06/28/2023 +description: Use PSCredential type +ms.date: 06/11/2026 ms.topic: reference title: UsePSCredentialType --- @@ -10,16 +10,14 @@ title: UsePSCredentialType ## Description -If the cmdlet or function has a **Credential** parameter, the parameter must accept the -**PSCredential** type. - -## How - -Change the **Credential** parameter's type to be **PSCredential**. +This rule detects when a cmdlet or function defines a **Credential** parameter with a type other +than **PSCredential**. Credential parameters should always use the **PSCredential** type to ensure +proper handling of secure credential objects. Change any **Credential** parameter's type to +**PSCredential** for consistency and security. ## Example -### Wrong +### Noncompliant ```powershell function Credential([String]$Credential) @@ -28,7 +26,7 @@ function Credential([String]$Credential) } ``` -### Correct +### Compliant ```powershell function Credential([PSCredential]$Credential) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseProcessBlockForPipelineCommand.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseProcessBlockForPipelineCommand.md index 2e563088..8c12c0a6 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseProcessBlockForPipelineCommand.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseProcessBlockForPipelineCommand.md @@ -1,6 +1,6 @@ --- -description: Use process block for command that accepts input from pipeline. -ms.date: 06/28/2023 +description: Use process block for commands that accept input from a pipeline +ms.date: 06/11/2026 ms.topic: reference title: UseProcessBlockForPipelineCommand --- @@ -10,13 +10,15 @@ title: UseProcessBlockForPipelineCommand ## Description -Functions that support pipeline input should always handle parameter input in a process block. -Unexpected behavior can result if input is handled directly in the body of a function where -parameters declare pipeline support. +This rule detects functions with pipeline-enabled parameters that handle input directly in the +function body instead of using a process block. Functions that accept pipeline input through +parameters should always process that input in a process block. Handling parameter input directly in +the function body can lead to unexpected behavior because the function body executes once, while the +process block executes for each object in the pipeline. ## Example -### Wrong +### Noncompliant ```powershell Function Get-Number @@ -32,14 +34,7 @@ Function Get-Number } ``` -#### Result - -``` -PS C:\> 1..5 | Get-Number -5 -``` - -### Correct +### Compliant ```powershell Function Get-Number @@ -57,14 +52,3 @@ Function Get-Number } } ``` - -#### Result - -``` -PS C:\> 1..5 | Get-Number -1 -2 -3 -4 -5 -``` diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseShouldProcessForStateChangingFunctions.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseShouldProcessForStateChangingFunctions.md index 8df5d285..8c571889 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseShouldProcessForStateChangingFunctions.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseShouldProcessForStateChangingFunctions.md @@ -1,6 +1,6 @@ --- -description: Use ShouldProcess For State Changing Functions -ms.date: 12/05/2024 +description: Use ShouldProcess for state changing functions +ms.date: 06/11/2026 ms.topic: reference title: UseShouldProcessForStateChangingFunctions --- @@ -10,12 +10,18 @@ title: UseShouldProcessForStateChangingFunctions ## Description -Functions whose verbs change system state should support `ShouldProcess`. To enable the -`ShouldProcess` feature, set the `SupportsShouldProcess` argument in the `CmdletBinding` attribute. -The `SupportsShouldProcess` argument adds **Confirm** and **WhatIf** parameters to the function. The -**Confirm** parameter prompts the user before it runs the command on each object in the pipeline. -The **WhatIf** parameter lists the changes that the command would make, instead of running the -command. +This rule detects functions with state-changing verbs that don't support `ShouldProcess`. Functions +whose verbs change system state should support `ShouldProcess` to provide users with the ability to +confirm or preview changes before execution. To enable this feature, set the `SupportsShouldProcess` +argument to `$true` in the `CmdletBinding` attribute. + +The `SupportsShouldProcess` argument automatically adds the **Confirm** and **WhatIf** parameters to +your function: + +- The **Confirm** parameter prompts the user to confirm the command before it runs on each object in + the pipeline. +- The **WhatIf** parameter displays the changes the command would make without actually running the + command. Verbs that should support `ShouldProcess`: @@ -28,13 +34,9 @@ Verbs that should support `ShouldProcess`: - `Reset` - `Update` -## How - -Include the `SupportsShouldProcess` argument in the `CmdletBinding` attribute. - ## Example -### Wrong +### Noncompliant ```powershell function Set-ServiceObject @@ -49,7 +51,7 @@ function Set-ServiceObject } ``` -### Correct +### Compliant ```powershell function Set-ServiceObject @@ -64,12 +66,12 @@ function Set-ServiceObject } ``` -## More information +## See also - [about_Functions_CmdletBindingAttribute][01] - [Everything you wanted to know about ShouldProcess][04] -- [Required Development Guidelines][03] -- [Requesting Confirmation from Cmdlets][02] +- [Required development guidelines][03] +- [Requesting confirmation from cmdlets][02] [01]: /powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute From 4387d3d6c5c3804245552b2ed3b0bfb7d39ab03a Mon Sep 17 00:00:00 2001 From: Xelu86 <103963494+Xelu86@users.noreply.github.com> Date: Mon, 15 Jun 2026 09:23:26 -0400 Subject: [PATCH 3/3] [Freshness] PSScriptAnalyzer Article Updates - Batch 16 (#420) * Freshness * Applied feedback --- .../Rules/AlignAssignmentStatement.md | 158 +++++------------- .../AvoidAssignmentToAutomaticVariable.md | 19 +-- .../AvoidDefaultValueForMandatoryParameter.md | 11 +- .../Rules/AvoidDefaultValueSwitchParameter.md | 32 ++-- 4 files changed, 67 insertions(+), 153 deletions(-) diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AlignAssignmentStatement.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AlignAssignmentStatement.md index 2aca4a24..18a2541a 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AlignAssignmentStatement.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AlignAssignmentStatement.md @@ -1,6 +1,6 @@ --- description: Align assignment statement -ms.date: 03/20/2026 +ms.date: 06/12/2026 ms.topic: reference title: AlignAssignmentStatement --- @@ -10,12 +10,20 @@ title: AlignAssignmentStatement ## Description -Consecutive assignment statements are easier to scan when their `=` signs line up vertically. +This rule detects misaligned assignment operators in hashtables and enum definitions. Consecutive +assignment statements are easier to read and maintain when their assignment operators align +vertically. -This rule looks at the key-value pairs in hashtables. Use this rule to align assignment operators in -multiline hashtables and enum definitions. +This rule checks key-value pairs in hashtables and enum member definitions to ensure that the `=` +signs line up. Use this rule to enforce consistent formatting in multiline hashtables and enum +definitions. -Consider the following example with a hashtable and enum that isn't aligned. +The rule ignores assignments within hashtables and enums that appear on the same line as other +assignments. For example, the rule ignores `$h = @{ a = 1; b = 2 }`. + +## Example + +### Noncompliant ```powershell $hashtable = @{ @@ -29,7 +37,7 @@ enum Enum { } ``` -Alignment in this case would look like the following. +### Compliant ```powershell $hashtable = @{ @@ -43,9 +51,6 @@ enum Enum { } ``` -The rule ignores assignments within hashtables and enums that appear on the same line as other -assignments. For example, the rule ignores `$h = @{ a = 1; b = 2 }`. - ## Configuration ```powershell @@ -61,126 +66,39 @@ Rules = @{ } ``` -### Parameters - -#### Enable: bool (Default value is `$false`) - -Enable or disable the rule during ScriptAnalyzer invocation. - -#### CheckHashtable: bool (Default value is `$true`) - -Enforce alignment of assignment statements in a hashtable and in a DSC Configuration. There's only -one setting for hashtable and DSC configuration because the property value pairs in a DSC -configuration are parsed as key-value pairs of a hashtable. - -#### AlignHashtableKvpWithInterveningComment: bool (Default value is `$true`) - -Include key-value pairs in the alignment that have an intervening comment, such as a comment between -the key name and the equals (`=`) sign. - -Consider this example: - -```powershell -$hashtable = @{ - property = 'value' - anotherProperty <#A Comment#> = 'another value' - anotherDifferentProperty = 'yet another value' -} -``` +## Parameters -With this setting **disabled**, the line with the comment is ignored, and the block is aligned -like so: +### Enable -```powershell -$hashtable = @{ - property = 'value' - anotherProperty <#A Comment#> = 'another value' - anotherDifferentProperty = 'yet another value' -} -``` +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`. -With it **enabled**, the line with the comment is included, and the block is aligned like so: +### CheckHashtable -```powershell -$hashtable = @{ - property = 'value' - anotherProperty <#A Comment#> = 'another value' - anotherDifferentProperty = 'yet another value' -} -``` +This parameter controls whether ScriptAnalyzer checks assignment alignment in hashtables and Desired +State Configuration (DSC) configurations. It accepts a boolean value. To disable this check, set +this parameter to `$false`. The default value is `$true`. -#### CheckEnum: bool (Default value is `$true`) +### AlignHashtableKvpWithInterveningComment -Enforce alignment of assignment statements of an Enum definition. +This parameter controls whether ScriptAnalyzer includes hashtable key-value pairs that contain an +intervening comment when determining alignment. It accepts a boolean value. To exclude these lines, +set this parameter to `$false`. The default value is `$true`. -#### AlignEnumMemberWithInterveningComment: bool (Default value is `$true`) +### CheckEnum -Include enum members in the alignment that have an intervening comment, such as a comment between -the member name and the equals (`=`) sign. +This parameter controls whether ScriptAnalyzer checks assignment alignment in enum member +definitions. It accepts a boolean value. To disable this check, set this parameter to `$false`. The +default value is `$true`. -Consider this example: +### AlignEnumMemberWithInterveningComment -```powershell -enum Enum { - member = 1 - anotherMember <#A Comment#> = 2 - anotherDifferentMember = 3 -} -``` +This parameter controls whether ScriptAnalyzer includes enum members that contain an intervening +comment when determining alignment. It accepts a boolean value. To exclude these lines, set this +parameter to `$false`. The default value is `$true`. -With this setting **disabled**, the line with the comment is ignored, and the block is aligned -like so: +### IncludeValuelessEnumMembers -```powershell -enum Enum { - member = 1 - anotherMember <#A Comment#> = 2 - anotherDifferentMember = 3 -} -``` - -With it **enabled**, the line with the comment is included, and the block is aligned like so: - -```powershell -enum Enum { - member = 1 - anotherMember <#A Comment#> = 2 - anotherDifferentMember = 3 -} -``` - -#### IncludeValuelessEnumMembers: bool (Default value is `$true`) - -Include enum members in the alignment that don't have an explicitly assigned value. Enums don't need -to be given a value when they're defined. - -Consider this example: - -```powershell -enum Enum { - member = 1 - anotherMember = 2 - anotherDifferentMember -} -``` - -With this setting **disabled**, the third line that has no value isn't considered when choosing -where to align assignments. It would be aligned like so: - -```powershell -enum Enum { - member = 1 - anotherMember = 2 - anotherDifferentMember -} -``` - -With it **enabled**, the valueless member is included in alignment as if it had a value: - -```powershell -enum Enum { - member = 1 - anotherMember = 2 - anotherDifferentMember -} -``` +This parameter controls whether ScriptAnalyzer includes enum members without explicitly assigned +values when determining alignment. It accepts a boolean value. To exclude valueless members, set +this parameter to `$false`. The default value is `$true`. diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md index d3cf9907..a483bf2a 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md @@ -1,6 +1,6 @@ --- description: Changing automatic variables might have undesired side effects -ms.date: 05/28/2026 +ms.date: 06/12/2026 ms.topic: reference title: AvoidAssignmentToAutomaticVariable --- @@ -10,16 +10,15 @@ title: AvoidAssignmentToAutomaticVariable ## Description -PowerShell automatically defines variables that store internal state information and manages them on -its own. Even though you _can_ override many automatic variables, doing so can have unexpected -effects for users. Assign automatic variables only in advanced, intentional scenarios. +This rule detects assignments to automatic variables and parameter names that use automatic variable +names. PowerShell automatically defines variables that store internal state information and manages +them on its own. Even though you _can_ override many automatic variables, doing so can have +unexpected effects for users and make your code harder to maintain and debug. -This rule helps you avoid assignments to automatic variables, which reduces hard-to-diagnose bugs -and keeps function behavior predictable. +Avoid using automatic variable names in your functions and parameters. Reserve automatic variables +for PowerShell's internal use only, and rely on them only to read state information. -Also use variable names in functions or parameters that don't conflict with automatic variables. - -To learn more about automatic variables, see [about_Automatic_Variables][01]. +To learn more, see [about_Automatic_Variables][01]. ## Example @@ -36,7 +35,7 @@ function foo($Error){ } function Get-CustomErrorMessage($ErrorMessage){ $Error = "Error occurred: $ErrorMessage" } ``` -### Preferred +### Compliant ```powershell function Get-CustomErrorMessage($ErrorMessage){ $FinalErrorMessage = "Error occurred: $ErrorMessage" } diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueForMandatoryParameter.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueForMandatoryParameter.md index 51374284..a43791fa 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueForMandatoryParameter.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueForMandatoryParameter.md @@ -1,6 +1,6 @@ --- description: Avoid Default Value For Mandatory Parameter -ms.date: 05/28/2026 +ms.date: 06/12/2026 ms.topic: reference title: AvoidDefaultValueForMandatoryParameter --- @@ -10,9 +10,10 @@ title: AvoidDefaultValueForMandatoryParameter ## Description -Mandatory parameters shouldn't have default values because there isn't a scenario where the default -can be used. PowerShell prompts for a value if the parameter value isn't specified when calling the -function. +This rule detects when mandatory parameters have default values assigned. Mandatory parameters +shouldn't have default values because they can't be used. When a parameter is marked as mandatory, +PowerShell always prompts the user for a value if one isn't supplied when calling the function. Any +default value assigned to a mandatory parameter is unreachable and serves no purpose. ## Example @@ -31,7 +32,7 @@ function Test } ``` -### Preferred +### Compliant ```powershell function Test diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md index 7ca78a59..e50d1505 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md @@ -1,6 +1,6 @@ --- -description: Switch Parameters Should Not Default To True -ms.date: 05/28/2026 +description: Switch parameters should not default to $true +ms.date: 06/12/2026 ms.topic: reference title: AvoidDefaultValueSwitchParameter --- @@ -10,24 +10,20 @@ title: AvoidDefaultValueSwitchParameter ## Description -If your parameter takes only `true` and `false`, define the parameter as type `[Switch]`. PowerShell -treats a switch parameter as `true` when it's used with a command. If the parameter isn't included -with the command, PowerShell considers the parameter to be false. Don't define `[Boolean]` -parameters. +This rule detects switch parameters that are assigned a default value of `$true`. Switch parameters +shouldn't have default values. By design, a switch parameter is `$false` when not specified and +`$true` when included in the command. Assigning a default value of `$true` to a switch parameter +violates this design principle and can cause unexpected behavior. -Don't define a switch parameter with a default value of `$true` because a switch parameter is -already `$false` when it isn't specified. Leave the switch parameter without a default value so it -behaves as designed. +If your parameter needs to accept only `true` and `false` values, use the `[Switch]` type instead of +`[Boolean]`. PowerShell automatically handles switch parameters correctly without requiring a +default value. -## How +To fix this issue, remove the default value from the switch parameter declaration. The switch +naturally defaults to `$false` when not specified, allowing your logic to respond appropriately to +the caller's input. -To fix this issue, don't assign a default value of `$true` to a `[switch]` parameter. Declare the -switch without a default value and write your logic so the parameter is treated as `$false` when -the caller doesn't supply it. - -## More information - -See [Strongly Encouraged Development Guidelines][01]. +To learn more, see [Strongly Encouraged Development Guidelines][01]. ## Example @@ -49,7 +45,7 @@ function Test-Script } ``` -### Preferred +### Compliant ```powershell function Test-Script