Replace throw with ThrowTerminatingError in exception handling#179
Replace throw with ThrowTerminatingError in exception handling#179johlju merged 6 commits intodsccommunity:mainfrom
Conversation
WalkthroughReplaces plain Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Caller as Caller
participant Helper as New-*Exception Helper
participant PS as PowerShell Runtime
Caller->>Helper: Invoke helper (message, PassThru?)
alt PassThru requested
Helper-->>Caller: return Exception object
else Terminating path
Helper->>Helper: build @errorSplat / New-ErrorRecord
Helper->>PS: $PSCmdlet.ThrowTerminatingError((New-ErrorRecord @errorSplat))
note right of PS #f8f3d7: Pipeline terminated with ErrorRecord
end
sequenceDiagram
autonumber
participant Caller as Caller
participant G as Get-LocalizedDataForInvariantCulture
participant FS as File System
participant PS as PowerShell Runtime
G->>FS: check localized language file
alt file missing
G->>PS: $PSCmdlet.ThrowTerminatingError(FileNotFound ErrorRecord)
else file found
G->>G: execute constrained scriptblock
alt script throws
G->>PS: $PSCmdlet.ThrowTerminatingError($_)
else success
G-->>Caller: return localized data
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Pre-merge checks✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
CHANGELOG.md (1)
10-14: Minor polish: format and wrap entry per guidelines
- Consider formatting ThrowTerminatingError and throw as inline code for readability.
- Optional: wrap Line 13 at ~80 chars to align with Markdown style.
source/Public/New-NotImplementedException.ps1 (1)
69-70: PassThru returns an Exception, not an ErrorRecord (update help text)Comment-based help says “returns the error record,” but the code returns the exception object. Update .OUTPUTS and the PassThru description accordingly.
source/Public/New-InvalidOperationException.ps1 (1)
72-73: Help text mismatch for PassThruHelp claims PassThru returns an “error record,” but code returns the exception object. Please update the help to reflect returning System.InvalidOperationException.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
CHANGELOG.md(1 hunks)source/Public/Get-LocalizedDataForInvariantCulture.ps1(2 hunks)source/Public/New-InvalidDataException.ps1(1 hunks)source/Public/New-InvalidOperationException.ps1(1 hunks)source/Public/New-InvalidResultException.ps1(1 hunks)source/Public/New-NotImplementedException.ps1(1 hunks)source/Public/New-ObjectNotFoundException.ps1(1 hunks)tests/Unit/Public/New-InvalidDataException.Tests.ps1(1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidResultException.ps1source/Public/New-ObjectNotFoundException.ps1source/Public/New-NotImplementedException.ps1source/Public/New-InvalidDataException.ps1CHANGELOG.mdtests/Unit/Public/New-InvalidDataException.Tests.ps1source/Public/New-InvalidOperationException.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidResultException.ps1source/Public/New-ObjectNotFoundException.ps1source/Public/New-NotImplementedException.ps1source/Public/New-InvalidDataException.ps1tests/Unit/Public/New-InvalidDataException.Tests.ps1source/Public/New-InvalidOperationException.ps1
source/**/*.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidResultException.ps1source/Public/New-ObjectNotFoundException.ps1source/Public/New-NotImplementedException.ps1source/Public/New-InvalidDataException.ps1source/Public/New-InvalidOperationException.ps1
**/*.md
⚙️ CodeRabbit configuration file
**/*.md: # Markdown Style Guidelines
- Wrap lines at word boundaries when over 80 characters (except tables/code blocks)
- Use 2 spaces for indentation
- Use '1.' for all items in ordered lists (1/1/1 numbering style)
- Disable
MD013rule by adding a comment for tables/code blocks exceeding 80 characters- Empty lines required before/after code blocks and headings (except before line 1)
- Escape backslashes in file paths only (not in code blocks)
- Code blocks must specify language identifiers
Text Formatting
- Parameters: bold
- Values/literals:
inline code- Resource/module/product names: italic
- Commands/files/paths:
inline code
Files:
CHANGELOG.md
CHANGELOG.md
⚙️ CodeRabbit configuration file
CHANGELOG.md: # Changelog Guidelines
- Always update the Unreleased section in CHANGELOG.md
- Use Keep a Changelog format
- Describe notable changes briefly, ≤2 items per change type
- Reference issues using format issue #<issue_number>
- No empty lines between list items in same section
- Skip adding entry if same change already exists in Unreleased section
- No duplicate sections or items in Unreleased section
Files:
CHANGELOG.md
tests/[Uu]nit/**/*.[Tt]ests.ps1
⚙️ CodeRabbit configuration file
tests/[Uu]nit/**/*.[Tt]ests.ps1: # Unit Tests Guidelines
- Test with localized strings: Use
InModuleScope -ScriptBlock { $script:localizedData.Key }- Mock files: Use
$TestDrivevariable (path to the test drive)- All public commands require parameter set validation tests
- After modifying classes, always run tests in new session (for changes to take effect)
Test Setup Requirements
Use this exact setup block before
Describe:[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] param () BeforeDiscovery { try { if (-not (Get-Module -Name 'DscResource.Test')) { # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) { # Redirect all streams to $null, except the error stream (stream 2) & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null } # If the dependencies have not been resolved, this will throw an error. Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' } } catch [System.IO.FileNotFoundException] { throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' } } BeforeAll { $script:moduleName = '{MyModuleName}' Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Mock:ModuleName'] = $script:moduleName $PSDefaultParameterValues['Should:ModuleName'] = $script:moduleName } AfterAll { $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') $PSDefaultParameterValues.Remove('Mock:ModuleNam...
Files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
**/*.[Tt]ests.ps1
⚙️ CodeRabbit configuration file
**/*.[Tt]ests.ps1: # Tests GuidelinesCore Requirements
- All public commands, private functions and classes must have unit tests
- All public commands and class-based resources must have integration tests
- Use Pester v5 syntax only
- Test code only inside
Describeblocks- Assertions only in
Itblocks- Never test verbose messages, debug messages or parameter binding behavior
- Pass all mandatory parameters to avoid prompts
Requirements
- Inside
Itblocks, assign unused return objects to$null(unless part of pipeline)- Tested entity must be called from within the
Itblocks- Keep results and assertions in same
Itblock- Avoid try-catch-finally for cleanup, use
AfterAllorAfterEach- Avoid unnecessary remove/recreate cycles
Naming
- One
Describeblock per file matching the tested entity nameContextdescriptions start with 'When'Itdescriptions start with 'Should', must not contain 'when'- Mock variables prefix: 'mock'
Structure & Scope
- Public commands: Never use
InModuleScope(unless retrieving localized strings)- Private functions/class resources: Always use
InModuleScope- Each class method = separate
Contextblock- Each scenario = separate
Contextblock- Use nested
Contextblocks for complex scenarios- Mocking in
BeforeAll(BeforeEachonly when required)- Setup/teardown in
BeforeAll,BeforeEach/AfterAll,AfterEachclose to usageSyntax Rules
- PascalCase:
Describe,Context,It,Should,BeforeAll,BeforeEach,AfterAll,AfterEach- Use
-BeTrue/-BeFalsenever-Be $true/-Be $false- Never use
Assert-MockCalled, useShould -Invokeinstead- No
Should -Not -Throw- invoke commands directly- Never add an empty
-MockWithblock- Omit
-MockWithwhen returning$null- Set
$PSDefaultParameterValuesforMock:ModuleName,Should:ModuleName,InModuleScope:ModuleName- Omit
-ModuleNameparameter on Pester commands- Never use
Mockinside `InModuleSc...
Files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
🧠 Learnings (30)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Do not use throw for terminating errors; instead use New-*Exception helper commands (e.g., New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException)
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : Do not use throw for terminating errors in classes
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : For terminating errors use $PSCmdlet.ThrowTerminatingError() (not in classes); include relevant error category and in catch include exception with localized message
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Use Write-Error for non-terminating errors with -Message (localized), -Category, -ErrorId (unique, matches localized ID), -TargetObject; in catch include -Exception; always return after Write-Error
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : For terminating errors, use New-*Exception cmdlets: New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-localization.instructions.md:0-0
Timestamp: 2025-08-29T17:22:23.268Z
Learning: Applies to source/**/*.ps1 : Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : For terminating errors use $PSCmdlet.ThrowTerminatingError() (not in classes); include relevant error category and in catch include exception with localized message
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidResultException.ps1source/Public/New-ObjectNotFoundException.ps1source/Public/New-InvalidDataException.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Use Write-Error for non-terminating errors with -Message (localized), -Category, -ErrorId (unique, matches localized ID), -TargetObject; in catch include -Exception; always return after Write-Error
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Do not use throw for terminating errors; instead use New-*Exception helper commands (e.g., New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException)
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidResultException.ps1source/Public/New-ObjectNotFoundException.ps1source/Public/New-NotImplementedException.ps1source/Public/New-InvalidDataException.ps1CHANGELOG.mdsource/Public/New-InvalidOperationException.ps1
📚 Learning: 2025-09-12T13:20:14.850Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : Do not use throw for terminating errors in classes
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidDataException.ps1
📚 Learning: 2025-08-29T17:22:23.268Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-localization.instructions.md:0-0
Timestamp: 2025-08-29T17:22:23.268Z
Learning: Applies to source/**/*.ps1 : Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-08-29T17:22:23.268Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-localization.instructions.md:0-0
Timestamp: 2025-08-29T17:22:23.268Z
Learning: Applies to source/**/*.ps1 : Use localized string keys instead of hardcoded strings in script output/messages
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-08-17T10:48:15.384Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2136
File: source/suffix.ps1:24-24
Timestamp: 2025-08-17T10:48:15.384Z
Learning: In source/suffix.ps1, the Write-Verbose message in the catch block for Import-SqlDscPreferredModule does not need localization because the exception message from Import-SqlDscPreferredModule is already localized by that command, making it an edge case exception to the localization guidelines.
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-08-29T17:22:23.268Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-localization.instructions.md:0-0
Timestamp: 2025-08-29T17:22:23.268Z
Learning: Applies to source/**/*.ps1 : Assume and use $script:localizedData for accessing localized strings
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Import localized strings at the top of the module using Get-LocalizedData
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use localized strings for all messages (e.g., Write-Verbose, Write-Error)
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:14.850Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : Use $this.localizedData provided by ResourceBase (do not manually populate)
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:34:44.689Z
Learning: Applies to tests/[Uu]nit/**/*.[Tt]ests.ps1 : In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/[a-z][a-z]-[A-Z][A-Z]/DSC_*.strings.psd1 : Additional localization folders must be named using Get-UICulture names (e.g., fr-FR) and contain DSC_<ResourceName>.strings.psd1
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:14.850Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : For terminating errors, use New-*Exception cmdlets: New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1source/Public/New-InvalidResultException.ps1source/Public/New-ObjectNotFoundException.ps1source/Public/New-NotImplementedException.ps1source/Public/New-InvalidDataException.ps1CHANGELOG.mdsource/Public/New-InvalidOperationException.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Avoid empty catch blocks; prefer -ErrorAction SilentlyContinue
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-06T19:12:11.414Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2189
File: source/Public/Set-SqlDscDatabaseDefault.ps1:124-130
Timestamp: 2025-09-06T19:12:11.414Z
Learning: In PowerShell functions, when calling commands with -ErrorAction 'Stop', if the command fails it throws a terminating error that stops execution of the calling function entirely, so $ErrorActionPreference restoration only needs to happen after successful completion, not in a finally block.
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:14.850Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : Use try/catch blocks for exception handling in classes
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Set $ErrorActionPreference='Stop' immediately before commands using -ErrorAction 'Stop' and restore after; do not use try-catch-finally for this
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use try/catch blocks to handle exceptions in MOF-based resources
Applied to files:
source/Public/Get-LocalizedDataForInvariantCulture.ps1
📚 Learning: 2025-08-17T18:25:52.891Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: source/Public/New-SqlDscLogin.ps1:218-225
Timestamp: 2025-08-17T18:25:52.891Z
Learning: PowerShell's System.Management.Automation.ErrorRecord constructor accepts a string as the first parameter and automatically converts it to an exception object internally. No need to manually wrap strings in System.Exception when creating ErrorRecord objects in PowerShell.
Applied to files:
source/Public/New-InvalidResultException.ps1source/Public/New-NotImplementedException.ps1
📚 Learning: 2025-09-16T16:32:58.363Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-09-16T16:32:58.363Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Avoid using ExpectedMessage with Should -Throw assertions
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mock variables must be prefixed with 'mock'
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use Assert-MockCalled; use Should -Invoke instead
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Omit -MockWith when returning $null
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Perform mocking in BeforeAll (use BeforeEach only when required)
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never add an empty -MockWith block
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Assertions only in It blocks
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-09-12T13:21:31.054Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-09-12T13:21:31.054Z
Learning: Applies to **/*.[Tt]ests.ps1 : Use Pester v5 syntax only
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
PR: dsccommunity/SqlServerDsc#2132
File: tests/Unit/Public/New-SqlDscLogin.Tests.ps1:0-0
Timestamp: 2025-08-18T13:50:53.789Z
Learning: In SqlServerDsc unit tests, SMO stub objects can be used to verify method calls like Create() on Login objects by adding mock verifications with Should -Invoke, providing more robust testing than just checking for no exceptions.
Applied to files:
tests/Unit/Public/New-InvalidDataException.Tests.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: dsccommunity.DscResource.Common (Build Package Module)
🔇 Additional comments (3)
source/Public/Get-LocalizedDataForInvariantCulture.ps1 (1)
204-205: LGTM: rethrowing original ErrorRecordRe-emitting the caught ErrorRecord via ThrowTerminatingError is correct and preserves context.
tests/Unit/Public/New-InvalidDataException.Tests.ps1 (1)
58-58: Test expectation update looks correctPattern-matching FullyQualifiedErrorId accommodates suffixes introduced via ThrowTerminatingError paths.
source/Public/New-InvalidDataException.ps1 (1)
45-45: Correct use of ThrowTerminatingErrorSwitching from throw (New-ErrorRecord ...) to $PSCmdlet.ThrowTerminatingError((New-ErrorRecord ...)) aligns with guidelines.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
source/Private/Clear-ZeroedEnumPropertyValue.ps1 (1)
40-47: Use hashtable indexer instead of dot-notation; simplify enum checkDot-notation can fail for keys with spaces/special chars. Use indexer on both read/write, and prefer casting the enum directly to [int].
Apply:
- $value = $InputObject.$property - if ($value -is [System.Enum] -and [System.Int32]$value.value__ -eq 0) + $value = $InputObject[$property] + if ($value -is [System.Enum] -and [int] $value -eq 0) { continue } - $result.$property = $value + $result[$property] = $value
🧹 Nitpick comments (3)
source/Private/Clear-ZeroedEnumPropertyValue.ps1 (3)
26-29: Validate input is not nullAdd ValidateNotNull() to match guidelines and avoid null pipeline inputs.
Apply:
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] + [ValidateNotNull()] [System.Collections.Hashtable] $InputObject
31-53: Pipeline behavior aggregates multiple inputs — confirm intentCurrent begin/process/end collects all pipeline inputs into one hashtable. If you intended one output per input, return within
processand dropbegin/end.Proposed shape (if per-input output is desired):
- begin - { - $result = @{} - } - - process - { - foreach ($property in $InputObject.Keys) - { - $value = $InputObject[$property] - if ($value -is [System.Enum] -and [int] $value -eq 0) - { - continue - } - - $result[$property] = $value - } - } - - end - { - return $result - } + process + { + $result = @{} + + foreach ($property in $InputObject.Keys) + { + $value = $InputObject[$property] + if ($value -is [System.Enum] -and [int] $value -eq 0) + { + continue + } + + $result[$property] = $value + } + + return $result + }
3-8: Fix “hashable” → “hashtable” in help textMinor doc typo in SYNOPSIS/DESCRIPTION.
Apply:
- Removes any properties from a hashable which have values that are + Removes any properties from a hashtable which have values that are @@ - Removes any properties from a hashable which have values that are + Removes any properties from a hashtable which have values that are
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
source/Private/Clear-ZeroedEnumPropertyValue.ps1(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**
⚙️ CodeRabbit configuration file
**: # DSC Community GuidelinesTerminology
- Command: Public command
- Function: Private function
- Resource: DSC class-based resource
Build & Test Workflow Requirements
- Run PowerShell script files from repository root
- Setup build and test environment (once per
pwshsession):./build.ps1 -Tasks noop- Build project before running tests:
./build.ps1 -Tasks build- Always run tests in new
pwshsession:Invoke-Pester -Path @({test paths}) -Output DetailedFile Organization
- Public commands:
source/Public/{CommandName}.ps1- Private functions:
source/Private/{FunctionName}.ps1- Unit tests:
tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1- Integration tests:
tests/Integration/Commands/{CommandName}.Integration.Tests.ps1Requirements
- Follow instructions over existing code patterns
- Follow PowerShell style and test guideline instructions strictly
- Always update CHANGELOG.md Unreleased section
- Localize all strings using string keys; remove any orphaned string keys
- Check DscResource.Common before creating private functions
- Separate reusable logic into private functions
- DSC resources should always be created as class-based resources
- Add unit tests for all commands/functions/resources
- Add integration tests for all public commands and resources
Files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}
⚙️ CodeRabbit configuration file
{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell GuidelinesNaming
- Use descriptive names (3+ characters, no abbreviations)
- Functions: PascalCase with Verb-Noun format using approved verbs
- Parameters: PascalCase
- Variables: camelCase
- Keywords: lower-case
- Classes: PascalCase
- Include scope for script/global/environment variables:
$script:,$global:,$env:File naming
- Class files:
###.ClassName.ps1format (e.g.001.SqlReason.ps1,004.StartupParameters.ps1)Formatting
Indentation & Spacing
- Use 4 spaces (no tabs)
- One space around operators:
$a = 1 + 2- One space between type and variable:
[String] $name- One space between keyword and parenthesis:
if ($condition)- No spaces on empty lines
- Try to limit lines to 120 characters
Braces
- Newline before opening brace (except variable assignments)
- One newline after opening brace
- Two newlines after closing brace (one if followed by another brace or continuation)
Quotes
- Use single quotes unless variable expansion is needed:
'text'vs"text $variable"Arrays
- Single line:
@('one', 'two', 'three')- Multi-line: each element on separate line with proper indentation
- Do not use the unary comma operator (
,) in return statements to force
an arrayHashtables
- Empty:
@{}- Each property on separate line with proper indentation
- Properties: Use PascalCase
Comments
- Single line:
# Comment(capitalized, on own line)- Multi-line:
<# Comment #>format (opening and closing brackets on own line), and indent text- No commented-out code
Comment-based help
- Always add comment-based help to all functions and scripts
- Comment-based help: SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, EXAMPLE sections before function/class
- Comment-based help indentation: keywords 4 spaces, text 8 spaces
- Include examples for all parameter sets and combinations
- INPUTS: List each pipeline‑accepted type (one per line) with a 1‑line description...
Files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
source/**/*.ps1
⚙️ CodeRabbit configuration file
source/**/*.ps1: # Localization GuidelinesRequirements
- Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
- Use localized string keys, not hardcoded strings
- Assume
$script:localizedDatais availableString Files
- Commands/functions:
source/en-US/{MyModuleName}.strings.psd1- Class resources:
source/en-US/{ResourceClassName}.strings.psd1Key Naming Patterns
- Format:
Verb_FunctionName_Action(underscore separators), e.g.Get_Database_ConnectingToDatabaseString Format
ConvertFrom-StringData @' KeyName = Message with {0} placeholder. (PREFIX0001) '@String IDs
- Format:
(PREFIX####)- PREFIX: First letter of each word in class or function name (SqlSetup → SS, Get-SqlDscDatabase → GSDD)
- Number: Sequential from 0001
Usage
Write-Verbose -Message ($script:localizedData.KeyName -f $value1)
Files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-09-12T13:20:57.155Z
Learning: Applies to source/DSCResources/**/*.psm1 : Do not use throw for terminating errors; instead use New-*Exception helper commands (e.g., New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException)
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : Do not use throw for terminating errors in classes
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : For terminating errors use $PSCmdlet.ThrowTerminatingError() (not in classes); include relevant error category and in catch include exception with localized message
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Use Write-Error for non-terminating errors with -Message (localized), -Category, -ErrorId (unique, matches localized ID), -TargetObject; in catch include -Exception; always return after Write-Error
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-09-12T13:20:14.850Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : For terminating errors, use New-*Exception cmdlets: New-InvalidDataException, New-ArgumentException, New-InvalidOperationException, New-ObjectNotFoundException, New-InvalidResultException, New-NotImplementedException
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-localization.instructions.md:0-0
Timestamp: 2025-08-29T17:22:23.268Z
Learning: Applies to source/**/*.ps1 : Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Place parameter attributes on separate lines
Applied to files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Put parameter type on the line above the parameter name
Applied to files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Separate parameters with a blank line
Applied to files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : If no parameters, use param (); otherwise, place opening and closing parentheses on their own lines
Applied to files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
📚 Learning: 2025-09-16T16:34:27.319Z
Learnt from: CR
PR: dsccommunity/SqlServerDsc#0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-09-16T16:34:27.319Z
Learning: Applies to **/*.{ps1,psm1} : Parameter block at the top of the function
Applied to files:
source/Private/Clear-ZeroedEnumPropertyValue.ps1
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: dsccommunity.DscResource.Common (Build Package Module)
🔇 Additional comments (1)
source/Private/Clear-ZeroedEnumPropertyValue.ps1 (1)
24-25: Param block formatting LGTMMoving
paramand(to separate lines aligns with the style guidelines. No functional impact.
johlju
left a comment
There was a problem hiding this comment.
@johlju reviewed 4 of 8 files at r1, 5 of 5 files at r2, all commit messages.
Reviewable status: all files reviewed, 5 unresolved discussions (waiting on @dan-hughes)
|
@coderabbitai create an issue to track this: source/Private/Clear-ZeroedEnumPropertyValue.ps1: Minor doc typo in SYNOPSIS/DESCRIPTION. Apply: @@ |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainI'll first examine the file to confirm the typo and then create an issue to track this documentation fix. @johlju I've created an issue to track this documentation typo fix. The issue has been assigned to you and includes the suggested change along with references to this PR and comment. 🏁 Script executed: Length of output: 342 🏁 Script executed: Length of output: 61 @johlju I've successfully created issue #181 to track the documentation typo fix. The issue confirms the typo exists in both the SYNOPSIS and DESCRIPTION sections where "hashable" should be "hashtable", and includes the suggested fix along with references to this PR and comment. The issue has been assigned to you as requested. 🧠 Learnings used |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainI'll first verify the typo and then create an issue to track this documentation fix. @johlju I've created an issue to track the documentation typo fix. The issue has been assigned to you and includes the context from this PR review along with the specific change needed to correct "hashable" to "hashtable" in the help text. 🏁 Script executed: Length of output: 342 🏁 Script executed: Length of output: 61 @johlju Perfect! I've confirmed the typo exists in the file and successfully created issue #182 to track this documentation fix: #182 The issue includes:
🧠 Learnings used |
Pull Request (PR) description
Replace use of throw with ThrowTerminatingError.
This Pull Request (PR) fixes the following issues
Task list
file CHANGELOG.md. Entry should say what was changed and how that
affects users (if applicable), and reference the issue being resolved
(if applicable).
DSC Community Testing Guidelines.
This change is