Skip to content

Add New-SqlDscDatabaseSnapshot command for SMO-based snapshot creation#2343

Merged
johlju merged 89 commits intomainfrom
copilot/add-new-sqldscdatabase-snapshot
Nov 24, 2025
Merged

Add New-SqlDscDatabaseSnapshot command for SMO-based snapshot creation#2343
johlju merged 89 commits intomainfrom
copilot/add-new-sqldscdatabase-snapshot

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Nov 1, 2025

Implements a new command to create SQL Server database snapshots using SMO, abstracting the complexity of snapshot creation and providing a DSC-friendly interface.

Changes

  • New command: New-SqlDscDatabaseSnapshot

    • Two parameter sets: ServerObject (with DatabaseName) and DatabaseObject (pipeline-friendly)
    • Edition validation: Enterprise, Developer, and Evaluation only
    • Delegates to New-SqlDscDatabase with DatabaseSnapshotBaseName parameter for consistent creation logic
    • Supports -Force, -Refresh, -WhatIf, and -Confirm parameters
  • Localized strings: Added DatabaseSnapshot_Create and DatabaseSnapshot_EditionNotSupported error messages

  • Unit tests: 16 tests covering both parameter sets, edition validation, and parameter validation

Usage

# From ServerObject
$serverObject = Connect-SqlDscDatabaseEngine -InstanceName 'MyInstance'
$serverObject | New-SqlDscDatabaseSnapshot -Name 'MyDB_Snapshot' -DatabaseName 'MyDatabase'

# From DatabaseObject (pipeline)
$databaseObject = $serverObject | Get-SqlDscDatabase -Name 'MyDatabase'
$databaseObject | New-SqlDscDatabaseSnapshot -Name 'MyDB_Snapshot' -Force

Notes

  • Command is creation-only; does not support modifying existing snapshots
  • FileGroup/DataFile parameters noted in original proposal but deferred as SMO automatically mirrors source database structure for snapshots
Original prompt

This section details on the original issue you should resolve

<issue_title>New-SqlDscDatabaseSnapshot: New command proposal</issue_title>
<issue_description>### Command proposal

This proposal is for a new command: New-SqlDscDatabaseSnapshot. The command will enable users to create SQL Server database snapshots using SMO, providing an automated and DSC-friendly approach to snapshot management. It will leverage the existing New-SqlDscDatabase command to perform the actual creation of the snapshot database object, ensuring consistency with other database creation workflows in the module.

The command should:

  • Accept a ServerObject (input via pipeline) and a Name for the snapshot in one parameter set.
  • Optionally, accept a DatabaseObject (input via pipeline) in a second parameter set, for scenarios where the database to snapshot is already known or being piped from another command.
  • Use SMO to create the snapshot by setting the DatabaseSnapshotBaseName property and optionally configuring FileGroups and DataFiles if the user provides file information, allowing control over snapshot file placement and structure.
  • Abstract the complexity of SMO snapshot creation, making it easy to integrate into DSC resources.
  • Not mention T-SQL alternatives; focus on SMO-based implementation.

Proposed parameters

Parameter Mandatory Data type Description Default value Allowed values
ServerObject Yes (Set 1) SMO Server The server instance object; can be provided via pipeline. None SMO Server
Name Yes (Set 1) String The name for the database snapshot. None Valid database name
DatabaseObject Yes (Set 2) SMO Database The source database object to snapshot; can be provided via pipeline. None SMO Database
FileGroup No SMO FileGroup[] Optional: filegroup objects for configuring snapshot file locations/structure. None SMO FileGroup[]
DataFile No SMO DataFile[] Optional: datafile objects to specify snapshot sparse file paths. None SMO DataFile[]
Other common parameters as needed for consistency with New-SqlDscDatabase (e.g., Credential, WhatIf, Confirm).

Special considerations or limitations

  • The command must set the DatabaseSnapshotBaseName property on the snapshot database object before creation, as required by SMO for snapshots.
  • If FileGroup and DataFile parameters are provided, the snapshot must mirror the logical file structure of the source database, and DataFile.FileName must be set to the desired sparse file path.
  • Use of the pipeline for ServerObject/DatabaseObject should be supported for integration in DSC and PowerShell workflows.
  • Should make use of New-SqlDscDatabase for the actual creation logic to maintain standardization and reuse.
  • Proper validation must be performed to ensure the source database exists, the snapshot name is unique, and the SQL Server edition supports snapshots.
  • Ensure the command provides clear error messaging for unsupported scenarios (e.g., missing permissions, unsupported edition, file path issues).
  • Document that the command is for snapshot creation only, and does not support modification of existing snapshots.</issue_description>

<agent_instructions>Follow instructions and guidelines in the repository.</agent_instructions>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.


This change is Reviewable

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 1, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Adds DatabaseFileSpec and DatabaseFileGroupSpec classes, SMO test stubs for FileGroup/DataFile, new conversion and creation cmdlets (New-/ConvertTo-/Add-SqlDscFileGroup/DataFile), New-SqlDscDatabaseSnapshot, extends New-SqlDscDatabase with -FileGroup, localization strings, CI updates, and many unit/integration tests.

Changes

Cohort / File(s) Summary
Docs & editor config
\.github/instructions/dsc-community-style-guidelines.instructions.md, \.github/instructions/dsc-community-style-guidelines-pester.instructions.md, \.vscode/settings.json, CHANGELOG.md
Add class/enum file-path guidance, Pester/style guidance, VS Code pwsh terminal profiles, and changelog entries for new commands/classes.
Spec classes
source/Classes/002.DatabaseFileSpec.ps1, source/Classes/004.DatabaseFileGroupSpec.ps1
New PowerShell classes DatabaseFileSpec and DatabaseFileGroupSpec with constructors and public properties to describe data files and filegroups.
Conversion & creation cmdlets
source/Public/ConvertTo-SqlDscDataFile.ps1, source/Public/ConvertTo-SqlDscFileGroup.ps1, source/Public/New-SqlDscDataFile.ps1, source/Public/New-SqlDscFileGroup.ps1, source/Public/Add-SqlDscFileGroup.ps1
New/updated functions to convert spec → SMO objects, create FileGroup/DataFile with multiple parameter sets (Standard/FromSpec/AsSpec), and add FileGroup objects to a Database; include ShouldProcess/Force/PassThru semantics.
Database & snapshot cmdlets
source/Public/New-SqlDscDatabase.ps1, source/Public/New-SqlDscDatabaseSnapshot.ps1
New-SqlDscDatabase gains -FileGroup (DatabaseFileGroupSpec[]); new New-SqlDscDatabaseSnapshot wrapper validates edition support, optionally synthesizes FileGroup specs, and delegates to New-SqlDscDatabase.
Localization
source/en-US/SqlServerDsc.strings.psd1
Add localized strings for snapshot creation, filegroup/datafile ShouldProcess captions/descriptions/confirmations, and primary-file placement validation.
SMO test stubs
tests/Unit/Stubs/SMO.cs
Add SMO stub types (FileGroup, FileGroupCollection, DataFile, DataFileCollection); change Database.FileGroups from HashtableFileGroupCollection; add DatabaseSnapshotBaseName initialization.
Integration tests & CI
azure-pipelines.yml, tests/Integration/Commands/*.Integration.Tests.ps1, tests/Integration/Commands/README.md
Add integration tests for new cmdlets and snapshot flows, update pipeline test group order, and update integration README entries.
Unit tests & QA
tests/Unit/Classes/*.Tests.ps1, tests/Unit/Public/*.Tests.ps1, tests/QA/module.tests.ps1
Add unit tests for spec classes and public cmdlets; update QA module tests to surface parse errors and add comment-help validation rules.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant User
    participant Snapshot as New-SqlDscDatabaseSnapshot
    participant DB as New-SqlDscDatabase
    participant FGcmd as New-SqlDscFileGroup
    participant ConvFG as ConvertTo-SqlDscFileGroup
    participant ConvDF as ConvertTo-SqlDscDataFile
    participant SMO

    Note over User,DB: User requests database or snapshot with -FileGroup specs
    alt Snapshot flow
        User->>Snapshot: Invoke New-SqlDscDatabaseSnapshot(params)
        Snapshot->>DB: Forward params (Name, FileGroup?, Refresh, ...)
    else Direct DB flow
        User->>DB: Invoke New-SqlDscDatabase(-FileGroup ...)
    end
    loop each FileGroupSpec
        DB->>FGcmd: New-SqlDscFileGroup(FileGroupSpec / AsSpec)
        FGcmd->>ConvFG: ConvertTo-SqlDscFileGroup(FileGroupSpec, Database)
        loop each DataFileSpec
            ConvFG->>ConvDF: ConvertTo-SqlDscDataFile(FileGroupObj, DataFileSpec)
            ConvDF-->>ConvFG: SMO DataFile
        end
        ConvFG-->>FGcmd: SMO FileGroup(with files)
        FGcmd-->>DB: FileGroup object
        DB->>SMO: Attach FileGroup/DataFiles to Database
    end
    SMO-->>DB: Database object
    DB-->>User: Return Database (or snapshot)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45–75 minutes

  • Files/areas needing extra attention:
    • Parameter-set branching and validation in New-SqlDscDataFile, New-SqlDscFileGroup, New-SqlDscDatabaseSnapshot, and New-SqlDscDatabase.
    • Mapping of nullable/optional spec properties (Size, MaxSize, Growth, GrowthType, IsPrimaryFile) in ConvertTo-* functions.
    • SMO stub changes in tests/Unit/Stubs/SMO.cs: collection semantics, indexers, Add behavior, and Database.FileGroups initialization.
    • ShouldProcess / Force / WhatIf behavior and correctness of localization keys/IDs used by cmdlets.
    • Extensive new unit/integration tests and pipeline ordering/integration with SMO stubs.

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically describes the main change: adding the New-SqlDscDatabaseSnapshot command for SMO-based snapshot creation.
Description check ✅ Passed The description is detailed and comprehensive, explaining the new command, its parameters, usage examples, and implementation approach.
Linked Issues check ✅ Passed The PR implements all core requirements from issue #2341: New-SqlDscDatabaseSnapshot command with ServerObject/DatabaseObject parameter sets, edition validation, delegation to New-SqlDscDatabase, proper error messaging, and comprehensive unit tests.
Out of Scope Changes check ✅ Passed While the PR extends beyond the snapshot command to include supporting infrastructure (new file group and data file classes/commands, SMO stubs, style guidelines), these are foundational changes necessary for the snapshot feature and align with the broader database file management enhancements.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI and others added 2 commits November 1, 2025 12:07
Co-authored-by: johlju <7189721+johlju@users.noreply.github.com>
Co-authored-by: johlju <7189721+johlju@users.noreply.github.com>
Copilot AI changed the title [WIP] Add New-SqlDscDatabaseSnapshot command for SQL Server Add New-SqlDscDatabaseSnapshot command for SMO-based snapshot creation Nov 1, 2025
Copilot AI requested a review from johlju November 1, 2025 12:16
@codecov
Copy link
Copy Markdown

codecov Bot commented Nov 1, 2025

Codecov Report

❌ Patch coverage is 99.35065% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 94%. Comparing base (0688805) to head (4b60a75).

Files with missing lines Patch % Lines
source/Public/Add-SqlDscFileGroup.ps1 90% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@          Coverage Diff          @@
##           main   #2343    +/-   ##
=====================================
  Coverage    94%     94%            
=====================================
  Files       154     162     +8     
  Lines      9338    9492   +154     
=====================================
+ Hits       8846    8999   +153     
- Misses      492     493     +1     
Flag Coverage Δ
unit 94% <99%> (+<1%) ⬆️
Files with missing lines Coverage Δ
source/Classes/002.DatabaseFileSpec.ps1 100% <100%> (ø)
source/Classes/004.DatabaseFileGroupSpec.ps1 100% <100%> (ø)
source/Public/ConvertTo-SqlDscDataFile.ps1 100% <100%> (ø)
source/Public/ConvertTo-SqlDscFileGroup.ps1 100% <100%> (ø)
source/Public/New-SqlDscDataFile.ps1 100% <100%> (ø)
source/Public/New-SqlDscDatabase.ps1 88% <100%> (+<1%) ⬆️
source/Public/New-SqlDscDatabaseSnapshot.ps1 100% <100%> (ø)
source/Public/New-SqlDscFileGroup.ps1 100% <100%> (ø)
source/Public/Add-SqlDscFileGroup.ps1 90% <90%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread source/Public/Add-SqlDscDataFile.ps1 Fixed
Comment thread source/Public/Add-SqlDscFileGroup.ps1 Fixed
Comment thread source/Public/New-SqlDscDataFile.ps1 Fixed
…oup by using real SMO Database and FileGroup objects
…scDataFile; add suppression for ScriptAnalyzer warning in function
@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 22, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 22, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1 (2)

52-171: Add coverage for AsSpec and WithDatabaseFromSpec parameter sets

The unit suite exercises WithDatabase and Standalone, but there are no scenarios for -AsSpec or WithDatabaseFromSpec (e.g., returning DatabaseFileGroupSpec, honoring Files/ReadOnly/IsDefault, and using FileGroupSpec with a Database). Adding dedicated Contexts for these paths would better align with the “cover all scenarios and code paths” guidance and help catch regressions in the spec workflows introduced by this cmdlet.


122-171: Consider using the standard parameter‑set validation template

The “Parameter validation” Context checks individual properties (mandatory, default set name, presence of WhatIf/Confirm, etc.), but the repo guidelines also prescribe a specific parameter‑set validation It‑block that asserts the full parameter‑list string per set. Adopting that template here (with -ForEach cases for the four parameter sets) would bring this test file fully in line with the shared patterns and make future signature drift easier to detect.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 973dc55 and ae8a1b6.

📒 Files selected for processing (5)
  • source/Public/Add-SqlDscFileGroup.ps1 (1 hunks)
  • source/Public/New-SqlDscDataFile.ps1 (1 hunks)
  • source/Public/New-SqlDscFileGroup.ps1 (1 hunks)
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1 (1 hunks)
  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1 (1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
tests/[Uu]nit/**/*.[Tt]ests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)

tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.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 $TestDrive variable (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-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
tests/Unit/Public/*.Tests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1

tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
**/*.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Follow PowerShell style and test guideline instructions strictly

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Add unit tests for all commands, functions, and resources

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
**/*.{ps1,psm1}

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format

**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include 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 in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
**/*.{ps1,psm1,cs}

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

Prefer SMO over T-SQL for SQL Server interactions

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
tests/Unit/**/*.Tests.ps1

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
**/*.[Tt]ests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)

**/*.[Tt]ests.ps1: 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
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings or creating an object using an internal class)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester ...

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
**/*.{ps1,psm1,psd1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files

Files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File Organization

  • Public commands: source/Public/{CommandName}.ps1
  • Private functions: source/Private/{FunctionName}.ps1
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.ps1
  • Unit tests: tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
  • Integration tests: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Requirements

  • 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:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
source/**/*.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)

source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))

Files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
source/Public/*.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Place public commands in source/Public/{CommandName}.ps1

Files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
🧠 Learnings (46)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Stubs/SMO.cs : Ensure SMO stub types are correctly implemented in tests/Stubs/SMO.cs for any used [Microsoft.SqlServer.Management.Smo.*] types
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Add unit tests for all commands, functions, and resources

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands, private functions and classes must have unit tests

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to tests/Unit/Public/*.Tests.ps1 : Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Have exactly one Describe block per file, and name it to match the tested entity

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Avoid unnecessary remove/recreate cycles in tests

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/Public/*.Tests.ps1 : Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-08-09T19:29:36.323Z
Learnt from: johlju
Repo: dsccommunity/DscResource.Test PR: 167
File: source/Private/Test-FileContainsClassResource.ps1:44-56
Timestamp: 2025-08-09T19:29:36.323Z
Learning: In the DscResource.Test repository, DSC resource attributes are consistently written as `[DscResource(...)]` rather than using variations like `[DscResourceAttribute()]` or fully qualified names like `[Microsoft.PowerShell.DesiredStateConfiguration.DscResource()]`. The Test-FileContainsClassResource function should focus on detecting the standard `[DscResource(...)]` pattern that is actually used in the codebase.

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : All public commands must include parameter set validation tests

Applied to files:

  • tests/Unit/Public/New-SqlDscFileGroup.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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-SqlDscFileGroup.Tests.ps1
  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Cover all scenarios and code paths in integration tests

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Cover all scenarios and code paths in tests

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-08-17T10:15:48.194Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: tests/Unit/Public/Remove-SqlDscLogin.Tests.ps1:36-39
Timestamp: 2025-08-17T10:15:48.194Z
Learning: Public command unit tests guideline: Never use InModuleScope unless accessing localized strings from $script:localizedData. PSDefaultParameterValues for InModuleScope should be kept in public command tests to support localized string retrieval when necessary.

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to tests/Unit/Public/*.Tests.ps1 : For public commands, never use InModuleScope (except when retrieving localized strings)

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to tests/Unit/{Private,Classes}/*.Tests.ps1 : For private functions and class resources, always use InModuleScope

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use Mock inside an InModuleScope block

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Do not use 'Should -Not -Throw'; invoke commands directly

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must not mock real SMO types; use SMO stub types from SMO.cs

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Create a separate Context block for each scenario

Applied to files:

  • tests/Unit/Public/New-SqlDscDataFile.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.{ps1,psm1} : Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to source/Public/*.ps1 : Place public commands in source/Public/{CommandName}.ps1

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Include examples for all parameter sets and combinations in comment-based help

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/Add-SqlDscFileGroup.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : For unused mandatory parameters in Set-TargetResource or Test-TargetResource, add a help comment: "Not used in <function_name>"

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Use named parameters in function calls

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
📚 Learning: 2025-10-03T15:27:24.417Z
Learnt from: Borgquite
Repo: dsccommunity/UpdateServicesDsc PR: 78
File: source/DSCResources/MSFT_UpdateServicesComputerTargetGroup/MSFT_UpdateServicesComputerTargetGroup.psm1:9-22
Timestamp: 2025-10-03T15:27:24.417Z
Learning: In the UpdateServicesDsc repository, MOF-based DSC resources follow a minimal comment-based help convention that includes only .SYNOPSIS and .PARAMETER sections. The .DESCRIPTION, .INPUTS, and .OUTPUTS sections are intentionally omitted, even though functions have [OutputType()] attributes. This is consistent across all existing DSC resources: MSFT_UpdateServicesServer, MSFT_UpdateServicesCleanup, and MSFT_UpdateServicesApprovalRule.

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Set-TargetResource and Test-TargetResource must have identical parameters

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:78-93
Timestamp: 2025-08-16T13:22:15.230Z
Learning: In PowerShell unit tests for parameter validation in SqlServerDsc, accessing parameter attributes directly like `$cmd.Parameters['ParameterName'].Attributes.Mandatory` works correctly because PowerShell automatically iterates through the array and returns the property values. Additional filtering to ParameterAttribute is not necessary when the parameter structure is known and controlled.

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Get-TargetResource: remove non-mandatory parameters that are never used

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type

Applied to files:

  • source/Public/New-SqlDscDataFile.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.cs : In Database Engine resources, add InstanceName, ServerName, and Credential to $this.ExcludeDscProperties

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Use one space between type and variable (e.g., [String] $name)

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-09-14T19:15:59.918Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-14T19:15:59.918Z
Learning: SqlServerDsc-specific guidelines and requirements override general project guidelines and requirements

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-08-28T17:10:34.765Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2150
File: source/Classes/020.SqlAgentAlert.ps1:198-217
Timestamp: 2025-08-28T17:10:34.765Z
Learning: DSC properties with default values (e.g., `$Ensure = 'Present'`) are always present in the properties hashtable passed to validation methods, even when not explicitly specified by the user.

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-08-16T13:15:17.108Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: source/Public/Get-SqlDscLogin.ps1:27-38
Timestamp: 2025-08-16T13:15:17.108Z
Learning: For PowerShell comment-based help .OUTPUTS sections: Each distinct return type should have its own .OUTPUTS entry with a description of when that type is returned, even if the underlying implementation uses array casting. This follows official PowerShell documentation standards where you list each return type on its own line under .OUTPUTS with clear descriptions of the conditions for each type.

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-08-16T13:15:17.108Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: source/Public/Get-SqlDscLogin.ps1:27-38
Timestamp: 2025-08-16T13:15:17.108Z
Learning: For PowerShell comment-based help in .OUTPUTS sections: Each distinct type that can be returned should have its own .OUTPUTS entry, even if the implementation technically always returns an array. This follows official PowerShell documentation standards and helps users understand what to expect in different usage scenarios.

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-09-13T10:13:47.123Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2204
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:67-68
Timestamp: 2025-09-13T10:13:47.123Z
Learning: According to official Microsoft PowerShell documentation, both .INPUTS and .OUTPUTS keywords should be repeated for each type in comment-based help: "Repeat this keyword for each input type" and "Repeat this keyword for each output type". The guideline should instruct to repeat both keywords, not use single blocks.

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Use [OutputType({return type})] for functions with output; use [OutputType()] when no output

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-03T15:27:39.511Z
Learnt from: Borgquite
Repo: dsccommunity/UpdateServicesDsc PR: 78
File: source/DSCResources/MSFT_UpdateServicesComputerTargetGroup/MSFT_UpdateServicesComputerTargetGroup.psm1:91-109
Timestamp: 2025-10-03T15:27:39.511Z
Learning: For MOF-based DSC resources in DSC Community repositories (files matching `source/DSCResources/MSFT_*/MSFT_*.psm1`), the comment-based help for `Get-TargetResource`, `Set-TargetResource`, and `Test-TargetResource` functions should NOT include `.OUTPUTS` sections, even though the general PowerShell guidelines require them. This is an established pattern in the DSC Community.

Applied to files:

  • source/Public/New-SqlDscFileGroup.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : For state-changing functions, use SupportsShouldProcess with immediate ShouldProcess checks before each change, set ConfirmImpact, follow required pattern, avoid Write-Verbose inside the block

Applied to files:

  • source/Public/New-SqlDscFileGroup.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). (2)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
  • GitHub Check: PSScriptAnalyzer
🔇 Additional comments (10)
tests/Unit/Public/New-SqlDscDataFile.Tests.ps1 (3)

52-120: LGTM!

The tests correctly call the public command directly without unnecessary InModuleScope wrapping. The test structure follows Pester guidelines, and assertions use proper syntax.


122-227: LGTM!

Parameter validation tests comprehensively cover all three parameter sets (Standard, FromSpec, AsSpec) and mandatory parameter requirements using the correct template format.


229-299: LGTM!

Comprehensive test coverage for AsSpec and FromSpec parameter sets, including property validation, PRIMARY filegroup constraint enforcement, and error scenarios. All tests correctly invoke the command directly.

source/Public/New-SqlDscDataFile.ps1 (6)

1-126: LGTM!

Comment-based help is comprehensive and follows guidelines with proper SYNOPSIS, DESCRIPTION, PARAMETER, EXAMPLE, INPUTS, and OUTPUTS sections. Multiple OUTPUTS sections correctly document different return types for each parameter set.


127-191: LGTM!

Function signature correctly implements SupportsShouldProcess with appropriate ConfirmImpact, declares multiple OutputType attributes for different parameter sets, and defines parameters with proper attributes and full type names.


193-196: LGTM!

Force parameter pattern correctly implemented per coding guidelines.


198-228: LGTM!

AsSpec parameter set logic correctly creates and populates DatabaseFileSpec objects, properly checking PSBoundParameters for optional parameters and using switch parameter .IsPresent.


230-280: LGTM!

PRIMARY filegroup constraint validation, ShouldProcess implementation, and DataFile creation logic are all correctly implemented following coding guidelines.


127-127: Verify the static analysis alert about example 2.

A GitHub Advanced Security alert flags that the parameter set cannot be determined for example 2. However, examining the example (lines 80-86), it clearly uses the Standard parameter set with -FileGroup, -Name, -FileName, -PassThru, and -Force parameters. This appears to be a false positive from the static analyzer.

Please confirm whether this is a known limitation of the static analyzer or if there's an actual issue with the example syntax that prevents parameter set resolution.

source/Public/New-SqlDscFileGroup.ps1 (1)

1-217: Cmdlet design, parameter sets, and help/behavior alignment look solid

The cmdlet wiring is consistent with the SqlServerDsc guidelines: parameter sets are well‑separated (WithDatabase, WithDatabaseFromSpec, AsSpec, Standalone), Database.Parent is validated with a localized terminating error, the Force + SupportsShouldProcess pattern is correctly implemented, and the AsSpec path cleanly returns DatabaseFileGroupSpec while the other sets return SMO FileGroup. Comment‑based help (.INPUTS/.OUTPUTS, examples) now matches both the signature and the actual behavior, including the spec workflow, so this looks good to merge from a design and correctness standpoint.

Comment thread source/Public/Add-SqlDscFileGroup.ps1
Comment thread tests/Unit/Public/New-SqlDscDataFile.Tests.ps1 Outdated
@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 22, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 22, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Member

@johlju johlju left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:lgtm:

@johlju reviewed 1 of 11 files at r2, 3 of 13 files at r3, 4 of 20 files at r4, 8 of 19 files at r5, 16 of 21 files at r6, 2 of 5 files at r7, 3 of 3 files at r8, all commit messages.
Reviewable status: all files reviewed, 15 unresolved discussions (waiting on @copilot)

@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 23, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 23, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
source/Public/New-SqlDscDatabaseSnapshot.ps1 (1)

149-149: Move verbose message after edition validation.

The verbose message states that the snapshot is being created, but it's written before edition validation. If the edition is not supported, users will see the "creating" message followed by an error, which is confusing.

Move this line to after line 189 (after edition validation passes), or change the message to indicate that the command is "preparing to create" or "validating requirements for" the snapshot.

-        Write-Verbose -Message ($script:localizedData.DatabaseSnapshot_Create -f $Name, $DatabaseName, $ServerObject.InstanceName)
-
         # Validate SQL Server edition supports snapshots
         $supportedEditions = @('Enterprise', 'Developer', 'EnterpriseCore', 'EnterpriseOrDeveloper')
 
         if ($ServerObject.EngineEdition -notin @('Enterprise', 'EnterpriseEvaluation'))
         {
             # Check edition name for older servers or evaluation
             $editionName = $ServerObject.Edition
 
             $isSupported = $false
 
             foreach ($supportedEdition in $supportedEditions)
             {
                 if ($editionName -like "*$supportedEdition*")
                 {
                     $isSupported = $true
                     break
                 }
             }
 
             # Also check for Evaluation edition
             if ($editionName -like '*Evaluation*')
             {
                 $isSupported = $true
             }
 
             if (-not $isSupported)
             {
                 $errorMessage = $script:localizedData.DatabaseSnapshot_EditionNotSupported -f $ServerObject.InstanceName, $editionName
 
                 $PSCmdlet.ThrowTerminatingError(
                     [System.Management.Automation.ErrorRecord]::new(
                         [System.InvalidOperationException]::new($errorMessage),
                         'NSDS0001', # cspell: disable-line
                         [System.Management.Automation.ErrorCategory]::InvalidOperation,
                         $ServerObject
                     )
                 )
             }
         }
+
+        Write-Verbose -Message ($script:localizedData.DatabaseSnapshot_Create -f $Name, $DatabaseName, $ServerObject.InstanceName)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c6ac9a0 and 4a4b5d6.

📒 Files selected for processing (3)
  • source/Public/New-SqlDscDatabaseSnapshot.ps1 (1 hunks)
  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1 (1 hunks)
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1 (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (13)
source/**/*.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-localization.instructions.md)

source/**/*.ps1: Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning, and $PSCmdlet.ThrowTerminatingError() messages
Use localized string keys instead of hardcoded strings in script output/messages
Assume and use $script:localizedData for accessing localized strings
When emitting messages, reference $script:localizedData.KeyName and format with the -f operator (e.g., Write-Verbose -Message ($script:localizedData.KeyName -f $value1))

Files:

  • source/Public/New-SqlDscDatabaseSnapshot.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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/New-SqlDscDatabaseSnapshot.ps1
source/Public/*.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Place public commands in source/Public/{CommandName}.ps1

Files:

  • source/Public/New-SqlDscDatabaseSnapshot.ps1
**/*.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Follow PowerShell style and test guideline instructions strictly

Files:

  • source/Public/New-SqlDscDatabaseSnapshot.ps1
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
**/*.{ps1,psm1}

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

**/*.{ps1,psm1}: Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format
Private PowerShell functions must follow the {Verb}-{Noun} naming format

**/*.{ps1,psm1}: Use descriptive names (3+ characters, no abbreviations)
Functions must use PascalCase with approved Verb-Noun format
Parameters use PascalCase
Variables use camelCase
Keywords are lower-case
Classes use PascalCase
Include scope for script/global/environment variables: $script:, $global:, $env:
Use one space around operators (e.g., $a = 1 + 2)
Use one space between type and variable (e.g., [String] $name)
Use one space between keyword and parenthesis (e.g., if ($condition))
Newline before opening brace except for variable assignments
One newline after opening brace
Two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed
Arrays single-line format: @('one','two','three')
Multi-line arrays: one element per line with proper indentation
Do not use unary comma in return statements to force an array
Empty hashtable as @{}
Hashtable properties each on their own line with proper indentation
Hashtable property names use PascalCase
Single-line comments start with #, capitalized, on their own line
Multi-line comments use <# #>, brackets on their own lines, text indented
No commented-out code
Always add comment-based help to all functions and scripts
Comment-based help must include 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 in comment-based help
INPUTS: list each pipeline-accepted type with one-line description; repeat keyword per type
OUTPUTS: list each return type with one-line description; repeat keyword per type; must match [OutputType()] and actual returns
.NOTES only if critical (constraints, side effects, security, version), ≤2 short sentences
Av...

Files:

  • source/Public/New-SqlDscDatabaseSnapshot.ps1
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
**/*.{ps1,psm1,cs}

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

Prefer SMO over T-SQL for SQL Server interactions

Files:

  • source/Public/New-SqlDscDatabaseSnapshot.ps1
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
**/*.{ps1,psm1,psd1}

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-powershell.instructions.md)

**/*.{ps1,psm1,psd1}: Use 4 spaces for indentation (no tabs)
No spaces on empty lines
Try to limit lines to 120 characters
End files with exactly one blank line
Use line endings as defined by .gitattributes
Allow a maximum of two consecutive newlines
No trailing whitespace on any line
Use UTF-8 encoding without BOM for all files

Files:

  • source/Public/New-SqlDscDatabaseSnapshot.ps1
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File Organization

  • Public commands: source/Public/{CommandName}.ps1
  • Private functions: source/Private/{FunctionName}.ps1
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.ps1
  • Unit tests: tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
  • Integration tests: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Requirements

  • 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/New-SqlDscDatabaseSnapshot.ps1
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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/New-SqlDscDatabaseSnapshot.ps1
  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
tests/[Uu]nit/**/*.[Tt]ests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-unit-tests.instructions.md)

tests/[Uu]nit/**/*.[Tt]ests.ps1: In unit tests, access localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
When mocking files in tests, use the $TestDrive variable for file system operations
All public commands must include parameter set validation tests
Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module
Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach
Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue

Files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.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 $TestDrive variable (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-SqlDscDatabaseSnapshot.Tests.ps1
tests/Unit/Public/*.Tests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Place unit tests for public commands in tests/Unit/Public/{Name}.Tests.ps1

tests/Unit/Public/*.Tests.ps1: For public commands, never use InModuleScope (except when retrieving localized strings)
Place public command unit tests under tests/Unit/Public/{Name}.Tests.ps1

Files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
tests/Unit/{Classes,Public,Private}/*.Tests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines.instructions.md)

Add unit tests for all commands, functions, and resources

Files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
tests/Unit/**/*.Tests.ps1

📄 CodeRabbit inference engine (.github/instructions/SqlServerDsc-guidelines.instructions.md)

tests/Unit/**/*.Tests.ps1: Unit tests must not mock real SMO types; use SMO stub types from SMO.cs
Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll
Unit tests that reference SMO types must load stubs via Add-Type -Path "$PSScriptRoot/../Stubs/SMO.cs"

Files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
**/*.[Tt]ests.ps1

📄 CodeRabbit inference engine (.github/instructions/dsc-community-style-guidelines-pester.instructions.md)

**/*.[Tt]ests.ps1: 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
Place executable test code only inside Describe blocks
Place assertions only in It blocks
Do not test verbose messages, debug messages, or parameter binding behavior
Pass all mandatory parameters in tests to avoid prompts
Inside It blocks, assign unused return objects to $null (unless part of a pipeline)
Invoke the tested entity from within It blocks
Keep result capture and assertions in the same It block
Avoid try/catch/finally for cleanup; use AfterAll or AfterEach instead
Avoid unnecessary remove/recreate cycles in tests
Have exactly one Describe block per file, and name it to match the tested entity
Context descriptions must start with 'When'
It descriptions must start with 'Should' and must not contain 'when'
Prefix variables used for mocks with 'mock'
Create a separate Context block for each scenario
Use nested Context blocks for complex scenarios
Define mocks in BeforeAll; use BeforeEach only when required
Place setup/teardown in the nearest appropriate BeforeAll, BeforeEach, AfterAll, or AfterEach to where it’s used
Use PascalCase for Pester keywords: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
Use -BeTrue/-BeFalse; never use -Be $true/-Be $false
Never use Assert-MockCalled; use Should -Invoke instead
Do not use 'Should -Not -Throw'; invoke commands directly
Never add an empty -MockWith block
Omit -MockWith when the mock should return $null
Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName
Omit the -ModuleName parameter on Pester commands
Never use Mock inside an InModuleScope block
Define variables for -ForEach in BeforeDiscovery (close to usage)
Use -ForEach only on Context and It blocks
Do not add param() inside Pester blocks when using -ForEach
Access test case properties directl...

Files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings or creating an object using an internal class)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester ...

Files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
🧠 Learnings (22)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Stubs/SMO.cs : Ensure SMO stub types are correctly implemented in tests/Stubs/SMO.cs for any used [Microsoft.SqlServer.Management.Smo.*] types
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Add unit tests for all commands, functions, and resources

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands, private functions and classes must have unit tests

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Cover all scenarios and code paths in integration tests

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : All public commands must include parameter set validation tests

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-08-16T13:22:15.230Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: tests/Unit/Public/Get-SqlDscLogin.Tests.ps1:78-93
Timestamp: 2025-08-16T13:22:15.230Z
Learning: In PowerShell unit tests for parameter validation in SqlServerDsc, accessing parameter attributes directly like `$cmd.Parameters['ParameterName'].Attributes.Mandatory` works correctly because PowerShell automatically iterates through the array and returns the property values. Additional filtering to ParameterAttribute is not necessary when the parameter structure is known and controlled.

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Use the provided Parameter Set Validation test template to assert command ParameterSetName and full parameter list string; for multiple parameter sets, supply multiple hashtables via -ForEach

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-09-12T13:20:57.155Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Set-TargetResource and Test-TargetResource must have identical parameters

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-08-28T17:10:34.765Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2150
File: source/Classes/020.SqlAgentAlert.ps1:198-217
Timestamp: 2025-08-28T17:10:34.765Z
Learning: DSC properties with default values (e.g., `$Ensure = 'Present'`) are always present in the properties hashtable passed to validation methods, even when not explicitly specified by the user.

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Set $PSDefaultParameterValues entries for Mock:ModuleName, Should:ModuleName, and InModuleScope:ModuleName

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Use the Parameter Properties template to assert a parameter is mandatory via $parameterInfo = (Get-Command -Name 'CommandName').Parameters['ParameterName']; $parameterInfo.Attributes.Mandatory | Should -BeTrue

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Pass all mandatory parameters in tests to avoid prompts

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to **/*.{ps1,psm1} : Public PowerShell commands must follow the {Verb}-SqlDsc{Noun} naming format

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1
📚 Learning: 2025-10-26T13:28:23.439Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : All parameters must use [Parameter()] attribute; mandatory parameters use [Parameter(Mandatory = $true)]

Applied to files:

  • tests/Unit/Public/New-SqlDscDatabaseSnapshot.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). (3)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
  • GitHub Check: PSScriptAnalyzer
  • GitHub Check: PSScriptAnalyzer
🔇 Additional comments (9)
source/Public/New-SqlDscDatabaseSnapshot.ps1 (5)

1-92: LGTM! Comprehensive comment-based help.

The comment-based help is thorough, with clear descriptions, multiple examples covering both parameter sets, and helpful notes about edition support and snapshot limitations.


93-138: LGTM! Function declaration and parameters follow guidelines.

The function follows the required naming pattern, includes proper attributes, and implements the Force parameter pattern correctly. The two parameter sets provide flexible usage options.


151-189: LGTM! Edition validation is thorough.

The edition validation correctly handles both the EngineEdition enum property and falls back to checking the Edition string property for older SQL Server versions or editions that don't have a specific enum value. The error handling follows guidelines with proper use of ThrowTerminatingError and localized messages.


191-239: LGTM! FileGroup auto-generation logic is well-designed.

The automatic FileGroup generation correctly:

  • Retrieves the source database structure using Get-SqlDscDatabase
  • Handles the Refresh parameter appropriately
  • Falls back to MasterDBPath when DefaultFile is not set
  • Creates sparse files with .ss extension mirroring the source database structure
  • Uses efficient List<T> collections

241-259: LGTM! Database creation and return logic is correct.

The command properly delegates to New-SqlDscDatabase with the correct parameters, including DatabaseSnapshotBaseName to indicate snapshot creation. The WhatIfPreference is correctly passed, and the return type is consistent with the [OutputType()] declaration.

tests/Unit/Public/New-SqlDscDatabaseSnapshot.Tests.ps1 (4)

1-63: LGTM! Test setup follows guidelines exactly.

The test setup includes the required Pester structure with proper module loading, SMO stub loading, environment variable setup, and cleanup. The platform-appropriate path handling for mocks is a good practice for cross-platform testing.


64-273: LGTM! Comprehensive test coverage for both parameter sets.

The tests thoroughly cover both the ServerObject and DatabaseObject parameter sets, including:

  • Basic snapshot creation
  • Auto-generation of FileGroups with proper file paths
  • Refresh parameter propagation
  • User-provided FileGroup support
  • MasterDBPath fallback when DefaultFile is not set
  • Proper parameter passing to New-SqlDscDatabase

The mock setup is appropriate and tests use Should -Invoke with parameter filters for precise verification.


275-411: LGTM! Edition validation tests are comprehensive.

The tests thoroughly validate edition support, including:

  • Proper error handling for unsupported editions (Standard)
  • Verification of error ID (NSDS0001) and category (InvalidOperation)
  • Confirmation that New-SqlDscDatabase is not called on validation failure
  • Support for Developer and Evaluation editions beyond Enterprise

The error assertions use proper Pester syntax with -PassThru for detailed verification.


413-470: LGTM! Parameter validation tests follow the required template.

The parameter validation tests correctly:

  • Use the required template structure with -ForEach for parameter sets
  • Verify the complete parameter list string for each parameter set
  • Test mandatory attributes for parameters, including filtering to specific parameter sets where needed
  • Cover all parameters that should be mandatory

The tests follow the established guidelines for parameter validation testing.

@johlju
Copy link
Copy Markdown
Member

johlju commented Nov 24, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 24, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Member

@johlju johlju left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@johlju reviewed 1 of 3 files at r9, 2 of 2 files at r10, all commit messages.
Reviewable status: all files reviewed, 15 unresolved discussions (waiting on @copilot)

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1 (2)

32-58: Cross‑test dependency on persistent source database could be brittle

This test suite assumes SqlDscIntegrationTestDatabase_Persistent already exists (created by other integration tests) and hard‑fails if it does not. If test ordering or selection changes (e.g., running this file in isolation), these tests will fail before executing any assertions.

Consider one of:

  • Explicitly creating the persistent database here when missing (possibly via a helper that avoids repeated recreate cycles), or
  • Documenting and enforcing the ordering/dependency in the integration test docs/CI configuration.

60-228: Good coverage and cleanup for snapshot scenarios

The contexts for ServerObject, DatabaseObject, custom FileGroup, and Refresh cover the main integration paths, and cleanup via AfterEach/AfterAll plus Disconnect-SqlDscDatabaseEngine is thorough and aligned with guidelines. As an optional enhancement, you could add a simple -WhatIf scenario to ensure no snapshot is created when dry‑running, but this is not strictly required given unit tests likely cover ShouldProcess semantics.

Based on learnings, this provides solid scenario coverage for a new public command.

source/Public/New-SqlDscDatabaseSnapshot.ps1 (1)

1-92: Tighten .INPUTS/.OUTPUTS descriptions and FileGroup parameter text

The overall help is good, but two small documentation nits:

  • .INPUTS/.OUTPUTS list only the types; per guidelines, each should have a one‑line description underneath (e.g., what the piped Server/Database represent, and what the returned Database object is).
  • The .PARAMETER FileGroup text says “When not specified, SQL Server will create sparse files…”, but in reality this command auto‑generates DatabaseFileGroupSpec/DatabaseFileSpec entries based on the source database and passes them to New-SqlDscDatabase. Consider rephrasing to make it clear the cmdlet is generating those specs (resulting in sparse files in the default data directory).

These are documentation only and don’t affect behavior.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a4b5d6 and 4b60a75.

📒 Files selected for processing (2)
  • source/Public/New-SqlDscDatabaseSnapshot.ps1 (1 hunks)
  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1 (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**

⚙️ CodeRabbit configuration file

**: # DSC Community Guidelines

Terminology

  • 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 pwsh session): ./build.ps1 -Tasks noop
  • Build project before running tests: ./build.ps1 -Tasks build
  • Always run tests in new pwsh session: Invoke-Pester -Path @({test paths}) -Output Detailed

File Organization

  • Public commands: source/Public/{CommandName}.ps1
  • Private functions: source/Private/{FunctionName}.ps1
  • Classes: source/Classes/{DependencyGroupNumber}.{ClassName}.ps1
  • Enums: source/Enum/{DependencyGroupNumber}.{EnumName}.ps1
  • Unit tests: tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1
  • Integration tests: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Requirements

  • 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/New-SqlDscDatabaseSnapshot.ps1
  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
{**/*.ps1,**/*.psm1,**/*.psd1}

⚙️ CodeRabbit configuration file

{**/*.ps1,**/*.psm1,**/*.psd1}: # PowerShell Guidelines

Naming

  • 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.ps1 format (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 array

Hashtables

  • 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/New-SqlDscDatabaseSnapshot.ps1
  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
source/**/*.ps1

⚙️ CodeRabbit configuration file

source/**/*.ps1: # Localization Guidelines

Requirements

  • Localize all Write-Debug, Write-Verbose, Write-Error, Write-Warning and $PSCmdlet.ThrowTerminatingError() messages
  • Use localized string keys, not hardcoded strings
  • Assume $script:localizedData is available

String Files

  • Commands/functions: source/en-US/{MyModuleName}.strings.psd1
  • Class resources: source/en-US/{ResourceClassName}.strings.psd1

Key Naming Patterns

  • Format: Verb_FunctionName_Action (underscore separators), e.g. Get_Database_ConnectingToDatabase

String 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/New-SqlDscDatabaseSnapshot.ps1
**/*.[Tt]ests.ps1

⚙️ CodeRabbit configuration file

**/*.[Tt]ests.ps1: # Tests Guidelines

Core 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 Describe blocks
  • Assertions only in It blocks
  • Never test verbose messages, debug messages or parameter binding behavior
  • Pass all mandatory parameters to avoid prompts

Requirements

  • Inside It blocks, assign unused return objects to $null (unless part of pipeline)
  • Tested entity must be called from within the It blocks
  • Keep results and assertions in same It block
  • Avoid try-catch-finally for cleanup, use AfterAll or AfterEach
  • Avoid unnecessary remove/recreate cycles

Naming

  • One Describe block per file matching the tested entity name
  • Context descriptions start with 'When'
  • It descriptions start with 'Should', must not contain 'when'
  • Mock variables prefix: 'mock'

Structure & Scope

  • Public commands: Never use InModuleScope (unless retrieving localized strings or creating an object using an internal class)
  • Private functions/class resources: Always use InModuleScope
  • Each class method = separate Context block
  • Each scenario = separate Context block
  • Use nested Context blocks for complex scenarios
  • Mocking in BeforeAll (BeforeEach only when required)
  • Setup/teardown in BeforeAll,BeforeEach/AfterAll,AfterEach close to usage

Syntax Rules

  • PascalCase: Describe, Context, It, Should, BeforeAll, BeforeEach, AfterAll, AfterEach
  • Use -BeTrue/-BeFalse never -Be $true/-Be $false
  • Never use Assert-MockCalled, use Should -Invoke instead
  • No Should -Not -Throw - invoke commands directly
  • Never add an empty -MockWith block
  • Omit -MockWith when returning $null
  • Set $PSDefaultParameterValues for Mock:ModuleName, Should:ModuleName, InModuleScope:ModuleName
  • Omit -ModuleName parameter on Pester ...

Files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1

⚙️ CodeRabbit configuration file

tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1: # Integration Tests Guidelines

Requirements

  • Location Commands: tests/Integration/Commands/{CommandName}.Integration.Tests.ps1
  • Location Resources: tests/Integration/Resources/{ResourceName}.Integration.Tests.ps1
  • No mocking - real environment only
  • Cover all scenarios and code paths
  • Use Get-ComputerName for computer names in CI
  • Avoid ExpectedMessage for Should -Throw assertions
  • Only run integration tests in CI unless explicitly instructed.
  • Call commands with -Force parameter where applicable (avoids prompting).
  • Use -ErrorAction 'Stop' on commands so failures surface immediately

Required Setup Block

[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'
}

Files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
🧠 Learnings (16)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Stubs/SMO.cs : Ensure SMO stub types are correctly implemented in tests/Stubs/SMO.cs for any used [Microsoft.SqlServer.Management.Smo.*] types
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Add integration tests for all public commands (and resources)

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must use Connect-SqlDscDatabaseEngine with correct CI credentials to open DB sessions

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.397Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.397Z
Learning: Applies to tests/Integration/**/*.Tests.ps1 : Integration tests must call Disconnect-SqlDscDatabaseEngine after Connect-SqlDscDatabaseEngine

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Cover all scenarios and code paths in integration tests

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place command integration tests at tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Integration/Commands/*.Integration.Tests.ps1 : Place integration tests for public commands in tests/Integration/Commands/{CommandName}.Integration.Tests.ps1

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:34:44.689Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 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 : Include the exact Pester setup block before Describe: SuppressMessage attribute with param (); BeforeDiscovery to ensure DscResource.Test is available (fallback to build.ps1 -Tasks 'noop') and Import-Module; BeforeAll to set $script:moduleName, import the module, and set PSDefaultParameterValues for InModuleScope/Mock/Should; AfterAll to remove those defaults and unload the tested module

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-09-16T16:35:31.909Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines.instructions.md:0-0
Timestamp: 2025-09-16T16:35:31.909Z
Learning: Applies to tests/Unit/{Classes,Public,Private}/*.Tests.ps1 : Add unit tests for all commands, functions, and resources

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-12T11:23:30.123Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Include the required Pester setup block (SuppressMessage param, BeforeDiscovery loading DscResource.Test, and BeforeAll importing the module)

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Applies to tests/Unit/**/*.Tests.ps1 : Unit tests must set $env:SqlServerDscCI = $true in BeforeAll and remove it in AfterAll

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-08-18T13:50:53.789Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 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/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-08-17T10:13:30.079Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:104-108
Timestamp: 2025-08-17T10:13:30.079Z
Learning: In SqlServerDsc unit tests, SMO object stubs (like Login objects) should have properly mocked Parent properties with correct Server stub types and valid InstanceName values, rather than handling null Parent scenarios in production code.

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:27:07.728Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-10-26T13:27:07.728Z
Learning: Applies to **/*.[Tt]ests.ps1 : Avoid unnecessary remove/recreate cycles in tests

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1
📚 Learning: 2025-10-26T13:26:13.396Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-10-26T13:26:13.396Z
Learning: Use DSCSQLTEST (DB Engine), SSRS (Reporting Services), and PBIRS (Power BI Report Server) instances in CI environment

Applied to files:

  • tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.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). (29)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - Reporting Services Commands SQL2022_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - Reporting Services Commands SQL2022_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - Reporting Services Commands SQL2019_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - Reporting Services Commands SQL2019_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - Reporting Services Commands SQL2017_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - BI Report Server Commands PowerBI_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - BI Report Server Commands PowerBI_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - SQL Server Integration SQL2022_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - SQL Server Integration SQL2022_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - SQL Server Integration SQL2019_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - SQL Server Integration SQL2019_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - Power BI Report Server Integration PowerBI_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - SQL Server Integration SQL2017_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Resources - Power BI Report Server Integration PowerBI_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server Commands SQL2022_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server (Prepared Image) Commands - Prepared Image SQL2022_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server (Prepared Image) Commands - Prepared Image SQL2022_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server Commands SQL2022_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server (Prepared Image) Commands - Prepared Image SQL2019_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server Commands SQL2019_WIN2025)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server (Prepared Image) Commands - Prepared Image SQL2019_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server Commands SQL2019_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server (Prepared Image) Commands - Prepared Image SQL2017_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Integration Test Commands - SQL Server Commands SQL2017_WIN2022)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Publish Code Coverage)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Determine DSC Resource Test Requirements)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test HQRM)
  • GitHub Check: dsccommunity.SqlServerDsc (Quality Test and Unit Test Unit)
  • GitHub Check: dsccommunity.SqlServerDsc (Build Package Module)
🔇 Additional comments (3)
tests/Integration/Commands/New-SqlDscDatabaseSnapshot.Integration.Tests.ps1 (1)

1-30: Integration Pester setup and module loading look correct

The SuppressMessage/param () header, BeforeDiscovery block loading DscResource.Test, and BeforeAll importing SqlServerDsc match the required integration test template. Nothing to change here.

Based on learnings, this follows the prescribed integration setup pattern.

source/Public/New-SqlDscDatabaseSnapshot.ps1 (2)

95-130: Wrapper ShouldProcess/WhatIf/Force pattern is sound

The pattern of:

  • Using SupportsShouldProcess = $true plus a Force parameter and the standard if ($Force.IsPresent -and -not $Confirm) { $ConfirmPreference = 'None' } block, and
  • Delegating change control to New-SqlDscDatabase by passing Force and WhatIf = $WhatIfPreference

gives callers consistent -WhatIf/-Confirm semantics without duplicating ShouldProcess messaging. This aligns with the guidelines and avoids double prompts while still honoring Force.

No changes needed here.

Also applies to: 132-138, 189-249


132-138: Source database existence is not explicitly validated when -FileGroup is supplied

Right now Get-SqlDscDatabase is only called inside the if (-not $PSBoundParameters.ContainsKey('FileGroup')) block to drive automatic FileGroup generation. If the caller supplies a custom -FileGroup, no pre‑check is done to ensure $DatabaseName actually exists; the command will delegate directly to New-SqlDscDatabase with DatabaseSnapshotBaseName = $DatabaseName and rely on downstream errors.

Given the PR objectives (“Validate inputs: verify source database exists... provide clear error messages”), this is a noticeable gap for the custom -FileGroup scenario.

A straightforward refactor is to always validate existence once, and only reuse the returned object for auto‑generation when needed, for example:

-    process
-    {
-        # Determine the server object and source database name based on parameter set
+    process
+    {
+        # Determine the server object and source database name based on parameter set
         if ($PSCmdlet.ParameterSetName -eq 'DatabaseObject')
         {
             $ServerObject = $DatabaseObject.Parent
             $DatabaseName = $DatabaseObject.Name
         }
 
-        # Validate SQL Server edition supports snapshots
+        # Validate SQL Server edition supports snapshots
         ...
 
-        # If FileGroup is not specified, automatically create file groups based on source database
-        if (-not $PSBoundParameters.ContainsKey('FileGroup'))
-        {
-            # Get the source database object
-            $getSqlDscDatabaseParameters = @{
-                ServerObject = $ServerObject
-                Name = $DatabaseName
-                ErrorAction = 'Stop'
-            }
-
-            if ($PSCmdlet.ParameterSetName -eq 'ServerObject' -and $Refresh.IsPresent)
-            {
-                $getSqlDscDatabaseParameters['Refresh'] = $true
-            }
-
-            $sourceDatabase = Get-SqlDscDatabase @getSqlDscDatabaseParameters
+        # Always verify that the source database exists
+        $getSqlDscDatabaseParameters = @{
+            ServerObject = $ServerObject
+            Name        = $DatabaseName
+            ErrorAction = 'Stop'
+        }
+
+        if ($PSCmdlet.ParameterSetName -eq 'ServerObject' -and $Refresh.IsPresent)
+        {
+            $getSqlDscDatabaseParameters['Refresh'] = $true
+        }
+
+        $sourceDatabase = Get-SqlDscDatabase @getSqlDscDatabaseParameters
+
+        # If FileGroup is not specified, automatically create file groups based on source database
+        if (-not $PSBoundParameters.ContainsKey('FileGroup'))
+        {
             ...
-            $FileGroup = $generatedFileGroups.ToArray()
+            $FileGroup = $generatedFileGroups.ToArray()
         }
 
         # Create the snapshot using New-SqlDscDatabase
         $newSqlDscDatabaseParameters = @{
             ServerObject = $ServerObject
             Name = $Name
             DatabaseSnapshotBaseName = $DatabaseName
             FileGroup = $FileGroup
             Force = $Force
             WhatIf = $WhatIfPreference
         }

This keeps the existing behavior for auto‑generation while ensuring a clear, early failure if the source database does not exist, even when the caller supplies their own FileGroup specs.

Also applies to: 191-239, 241-256

⛔ Skipped due to learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Force parameter pattern: if ($Force.IsPresent -and -not $Confirm) { $ConfirmPreference = 'None' }
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2132
File: source/Public/New-SqlDscLogin.ps1:254-257
Timestamp: 2025-08-18T10:44:38.990Z
Learning: When implementing Force and Confirm parameter interaction in PowerShell functions with SupportsShouldProcess, use the pattern `if ($Force.IsPresent -and -not $Confirm)` to suppress confirmations. This ensures that explicit `-Confirm:$true` is respected even when `-Force` is present, preserving user intent when they explicitly request confirmation alongside Force.
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2136
File: source/Public/Remove-SqlDscLogin.ps1:83-86
Timestamp: 2025-08-17T10:03:59.993Z
Learning: In PowerShell functions with SupportsShouldProcess, the $Confirm automatic variable defaults to $false when no -Confirm parameter is passed, and only becomes $true when -Confirm or -Confirm:$true is explicitly passed. The logic `if ($Force.IsPresent -and -not $Confirm)` correctly handles both cases where no -Confirm is passed and where -Confirm:$false is explicitly passed.
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Include a Force switch for functions that use $PSCmdlet.ShouldContinue or $PSCmdlet.ShouldProcess
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : For state-changing functions, use SupportsShouldProcess with immediate ShouldProcess checks before each change, set ConfirmImpact, follow required pattern, avoid Write-Verbose inside the block
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-integration-tests.instructions.md:0-0
Timestamp: 2025-10-12T11:23:30.123Z
Learning: Applies to tests/[iI]ntegration/**/*.[iI]ntegration.[tT]ests.ps1 : Call commands with -Force where applicable to avoid prompting
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-10-26T13:28:23.439Z
Learning: Applies to **/*.{ps1,psm1} : Set $ErrorActionPreference = 'Stop' before commands using -ErrorAction 'Stop'; restore previous value after (no try-catch-finally)

@johlju johlju merged commit f49e80a into main Nov 24, 2025
5 of 9 checks passed
@johlju johlju deleted the copilot/add-new-sqldscdatabase-snapshot branch November 24, 2025 19:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

New-SqlDscDatabaseSnapshot: New command proposal

3 participants