|
| 1 | +--- |
| 2 | +applyTo: '**/*.ps1,**/*.psm1' |
| 3 | +description: 'PowerShell cmdlet and scripting best practices based on Microsoft guidelines' |
| 4 | +--- |
| 5 | + |
| 6 | +# PowerShell Cmdlet Development Guidelines |
| 7 | + |
| 8 | +This guide provides PowerShell-specific instructions to help GitHub Copilot generate idiomatic, safe, and maintainable scripts. It aligns with Microsoft’s PowerShell cmdlet development guidelines. |
| 9 | + |
| 10 | +## Naming Conventions |
| 11 | + |
| 12 | +- **Verb-Noun Format:** |
| 13 | + - Use approved PowerShell verbs (Get-Verb) |
| 14 | + - Use singular nouns |
| 15 | + - PascalCase for both verb and noun |
| 16 | + - Avoid special characters and spaces |
| 17 | + |
| 18 | +- **Parameter Names:** |
| 19 | + - Use PascalCase |
| 20 | + - Choose clear, descriptive names |
| 21 | + - Use singular form unless always multiple |
| 22 | + - Follow PowerShell standard names |
| 23 | + |
| 24 | +- **Variable Names:** |
| 25 | + - Use PascalCase for public variables |
| 26 | + - Use camelCase for private variables |
| 27 | + - Avoid abbreviations |
| 28 | + - Use meaningful names |
| 29 | + |
| 30 | +- **Alias Avoidance:** |
| 31 | + - Use full cmdlet names |
| 32 | + - Avoid using aliases in scripts (e.g., use Get-ChildItem instead of gci) |
| 33 | + - Document any custom aliases |
| 34 | + - Use full parameter names |
| 35 | + |
| 36 | +### Example |
| 37 | + |
| 38 | +```powershell |
| 39 | +function Get-UserProfile { |
| 40 | + [CmdletBinding()] |
| 41 | + param( |
| 42 | + [Parameter(Mandatory)] |
| 43 | + [string]$Username, |
| 44 | +
|
| 45 | + [Parameter()] |
| 46 | + [ValidateSet('Basic', 'Detailed')] |
| 47 | + [string]$ProfileType = 'Basic' |
| 48 | + ) |
| 49 | +
|
| 50 | + process { |
| 51 | + # Logic here |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +## Parameter Design |
| 57 | + |
| 58 | +- **Standard Parameters:** |
| 59 | + - Use common parameter names (`Path`, `Name`, `Force`) |
| 60 | + - Follow built-in cmdlet conventions |
| 61 | + - Use aliases for specialized terms |
| 62 | + - Document parameter purpose |
| 63 | + |
| 64 | +- **Parameter Names:** |
| 65 | + - Use singular form unless always multiple |
| 66 | + - Choose clear, descriptive names |
| 67 | + - Follow PowerShell conventions |
| 68 | + - Use PascalCase formatting |
| 69 | + |
| 70 | +- **Type Selection:** |
| 71 | + - Use common .NET types |
| 72 | + - Implement proper validation |
| 73 | + - Consider ValidateSet for limited options |
| 74 | + - Enable tab completion where possible |
| 75 | + |
| 76 | +- **Switch Parameters:** |
| 77 | + - Use [switch] for boolean flags |
| 78 | + - Avoid $true/$false parameters |
| 79 | + - Default to $false when omitted |
| 80 | + - Use clear action names |
| 81 | + |
| 82 | +### Example |
| 83 | + |
| 84 | +```powershell |
| 85 | +function Set-ResourceConfiguration { |
| 86 | + [CmdletBinding()] |
| 87 | + param( |
| 88 | + [Parameter(Mandatory)] |
| 89 | + [string]$Name, |
| 90 | + |
| 91 | + [Parameter()] |
| 92 | + [ValidateSet('Dev', 'Test', 'Prod')] |
| 93 | + [string]$Environment = 'Dev', |
| 94 | + |
| 95 | + [Parameter()] |
| 96 | + [switch]$Force, |
| 97 | + |
| 98 | + [Parameter()] |
| 99 | + [ValidateNotNullOrEmpty()] |
| 100 | + [string[]]$Tags |
| 101 | + ) |
| 102 | + |
| 103 | + process { |
| 104 | + # Logic here |
| 105 | + } |
| 106 | +} |
| 107 | +``` |
| 108 | + |
| 109 | +## Pipeline and Output |
| 110 | + |
| 111 | +- **Pipeline Input:** |
| 112 | + - Use `ValueFromPipeline` for direct object input |
| 113 | + - Use `ValueFromPipelineByPropertyName` for property mapping |
| 114 | + - Implement Begin/Process/End blocks for pipeline handling |
| 115 | + - Document pipeline input requirements |
| 116 | + |
| 117 | +- **Output Objects:** |
| 118 | + - Return rich objects, not formatted text |
| 119 | + - Use PSCustomObject for structured data |
| 120 | + - Avoid Write-Host for data output |
| 121 | + - Enable downstream cmdlet processing |
| 122 | + |
| 123 | +- **Pipeline Streaming:** |
| 124 | + - Output one object at a time |
| 125 | + - Use process block for streaming |
| 126 | + - Avoid collecting large arrays |
| 127 | + - Enable immediate processing |
| 128 | + |
| 129 | +- **PassThru Pattern:** |
| 130 | + - Default to no output for action cmdlets |
| 131 | + - Implement `-PassThru` switch for object return |
| 132 | + - Return modified/created object with `-PassThru` |
| 133 | + - Use verbose/warning for status updates |
| 134 | + |
| 135 | +### Example |
| 136 | + |
| 137 | +```powershell |
| 138 | +function Update-ResourceStatus { |
| 139 | + [CmdletBinding()] |
| 140 | + param( |
| 141 | + [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] |
| 142 | + [string]$Name, |
| 143 | +
|
| 144 | + [Parameter(Mandatory)] |
| 145 | + [ValidateSet('Active', 'Inactive', 'Maintenance')] |
| 146 | + [string]$Status, |
| 147 | +
|
| 148 | + [Parameter()] |
| 149 | + [switch]$PassThru |
| 150 | + ) |
| 151 | +
|
| 152 | + begin { |
| 153 | + Write-Verbose "Starting resource status update process" |
| 154 | + $timestamp = Get-Date |
| 155 | + } |
| 156 | +
|
| 157 | + process { |
| 158 | + # Process each resource individually |
| 159 | + Write-Verbose "Processing resource: $Name" |
| 160 | + |
| 161 | + $resource = [PSCustomObject]@{ |
| 162 | + Name = $Name |
| 163 | + Status = $Status |
| 164 | + LastUpdated = $timestamp |
| 165 | + UpdatedBy = $env:USERNAME |
| 166 | + } |
| 167 | +
|
| 168 | + # Only output if PassThru is specified |
| 169 | + if ($PassThru) { |
| 170 | + Write-Output $resource |
| 171 | + } |
| 172 | + } |
| 173 | +
|
| 174 | + end { |
| 175 | + Write-Verbose "Resource status update process completed" |
| 176 | + } |
| 177 | +} |
| 178 | + ``` |
| 179 | + |
| 180 | +## Error Handling and Safety |
| 181 | + |
| 182 | +- **ShouldProcess Implementation:** |
| 183 | + - Use `[CmdletBinding(SupportsShouldProcess = $true)]` |
| 184 | + - Set appropriate `ConfirmImpact` level |
| 185 | + - Call `$PSCmdlet.ShouldProcess()` for system changes |
| 186 | + - Use `ShouldContinue()` for additional confirmations |
| 187 | + |
| 188 | +- **Message Streams:** |
| 189 | + - `Write-Verbose` for operational details with `-Verbose` |
| 190 | + - `Write-Warning` for warning conditions |
| 191 | + - `Write-Error` for non-terminating errors |
| 192 | + - `throw` for terminating errors |
| 193 | + - Avoid `Write-Host` except for user interface text |
| 194 | + |
| 195 | +- **Error Handling Pattern:** |
| 196 | + - Use try/catch blocks for error management |
| 197 | + - Set appropriate ErrorAction preferences |
| 198 | + - Return meaningful error messages |
| 199 | + - Use ErrorVariable when needed |
| 200 | + - Include proper terminating vs non-terminating error handling |
| 201 | + |
| 202 | +- **Non-Interactive Design:** |
| 203 | + - Accept input via parameters |
| 204 | + - Avoid `Read-Host` in scripts |
| 205 | + - Support automation scenarios |
| 206 | + - Document all required inputs |
| 207 | + |
| 208 | +### Example |
| 209 | + |
| 210 | +```powershell |
| 211 | +function Remove-UserAccount { |
| 212 | + [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] |
| 213 | + param( |
| 214 | + [Parameter(Mandatory, ValueFromPipeline)] |
| 215 | + [ValidateNotNullOrEmpty()] |
| 216 | + [string]$Username, |
| 217 | +
|
| 218 | + [Parameter()] |
| 219 | + [switch]$Force |
| 220 | + ) |
| 221 | +
|
| 222 | + begin { |
| 223 | + Write-Verbose "Starting user account removal process" |
| 224 | + $ErrorActionPreference = 'Stop' |
| 225 | + } |
| 226 | +
|
| 227 | + process { |
| 228 | + try { |
| 229 | + # Validation |
| 230 | + if (-not (Test-UserExists -Username $Username)) { |
| 231 | + Write-Error "User account '$Username' not found" |
| 232 | + return |
| 233 | + } |
| 234 | +
|
| 235 | + # Confirmation |
| 236 | + $shouldProcessMessage = "Remove user account '$Username'" |
| 237 | + if ($Force -or $PSCmdlet.ShouldProcess($Username, $shouldProcessMessage)) { |
| 238 | + Write-Verbose "Removing user account: $Username" |
| 239 | + |
| 240 | + # Main operation |
| 241 | + Remove-ADUser -Identity $Username -ErrorAction Stop |
| 242 | + Write-Warning "User account '$Username' has been removed" |
| 243 | + } |
| 244 | + } |
| 245 | + catch [Microsoft.ActiveDirectory.Management.ADException] { |
| 246 | + Write-Error "Active Directory error: $_" |
| 247 | + throw |
| 248 | + } |
| 249 | + catch { |
| 250 | + Write-Error "Unexpected error removing user account: $_" |
| 251 | + throw |
| 252 | + } |
| 253 | + } |
| 254 | +
|
| 255 | + end { |
| 256 | + Write-Verbose "User account removal process completed" |
| 257 | + } |
| 258 | +} |
| 259 | +``` |
| 260 | + |
| 261 | +## Documentation and Style |
| 262 | + |
| 263 | +- **Comment-Based Help:** Include comment-based help for any public-facing function or cmdlet. Inside the function, add a `<# ... #>` help comment with at least: |
| 264 | + - `.SYNOPSIS` Brief description |
| 265 | + - `.DESCRIPTION` Detailed explanation |
| 266 | + - `.EXAMPLE` sections with practical usage |
| 267 | + - `.PARAMETER` descriptions |
| 268 | + - `.OUTPUTS` Type of output returned |
| 269 | + - `.NOTES` Additional information |
| 270 | + |
| 271 | +- **Consistent Formatting:** |
| 272 | + - Follow consistent PowerShell style |
| 273 | + - Use proper indentation (4 spaces recommended) |
| 274 | + - Opening braces on same line as statement |
| 275 | + - Closing braces on new line |
| 276 | + - Use line breaks after pipeline operators |
| 277 | + - PascalCase for function and parameter names |
| 278 | + - Avoid unnecessary whitespace |
| 279 | + |
| 280 | +- **Pipeline Support:** |
| 281 | + - Implement Begin/Process/End blocks for pipeline functions |
| 282 | + - Use ValueFromPipeline where appropriate |
| 283 | + - Support pipeline input by property name |
| 284 | + - Return proper objects, not formatted text |
| 285 | + |
| 286 | +- **Avoid Aliases:** Use full cmdlet names and parameters |
| 287 | + - Avoid using aliases in scripts (e.g., use Get-ChildItem instead of gci); aliases are acceptable for interactive shell use. |
| 288 | + - Use `Where-Object` instead of `?` or `where` |
| 289 | + - Use `ForEach-Object` instead of `%` |
| 290 | + - Use `Get-ChildItem` instead of `ls` or `dir` |
| 291 | + |
| 292 | +## Full Example: End-to-End Cmdlet Pattern |
| 293 | + |
| 294 | +```powershell |
| 295 | +function New-Resource { |
| 296 | + [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] |
| 297 | + param( |
| 298 | + [Parameter(Mandatory = $true, |
| 299 | + ValueFromPipeline = $true, |
| 300 | + ValueFromPipelineByPropertyName = $true)] |
| 301 | + [ValidateNotNullOrEmpty()] |
| 302 | + [string]$Name, |
| 303 | +
|
| 304 | + [Parameter()] |
| 305 | + [ValidateSet('Development', 'Production')] |
| 306 | + [string]$Environment = 'Development' |
| 307 | + ) |
| 308 | + |
| 309 | + begin { |
| 310 | + Write-Verbose "Starting resource creation process" |
| 311 | + } |
| 312 | + |
| 313 | + process { |
| 314 | + try { |
| 315 | + if ($PSCmdlet.ShouldProcess($Name, "Create new resource")) { |
| 316 | + # Resource creation logic here |
| 317 | + Write-Output ([PSCustomObject]@{ |
| 318 | + Name = $Name |
| 319 | + Environment = $Environment |
| 320 | + Created = Get-Date |
| 321 | + }) |
| 322 | + } |
| 323 | + } |
| 324 | + catch { |
| 325 | + Write-Error "Failed to create resource: $_" |
| 326 | + } |
| 327 | + } |
| 328 | + |
| 329 | + end { |
| 330 | + Write-Verbose "Completed resource creation process" |
| 331 | + } |
| 332 | +} |
| 333 | +``` |
0 commit comments