Skip to content

SqlServerBase: Support connection protocol and port#2382

Merged
johlju merged 5 commits intodsccommunity:mainfrom
johlju:f/sqlresourcebase-protocol-and-port
Dec 28, 2025
Merged

SqlServerBase: Support connection protocol and port#2382
johlju merged 5 commits intodsccommunity:mainfrom
johlju:f/sqlresourcebase-protocol-and-port

Conversation

@johlju
Copy link
Copy Markdown
Member

@johlju johlju commented Dec 28, 2025

Pull Request (PR) description

  • Added public command Get-SqlDscServerProtocolTcpIp to retrieve TCP/IP address
    group information for SQL Server instances. Returns ServerIPAddress objects
    containing port configuration including TcpPort, TcpDynamicPorts, Enabled,
    and Active properties. Supports filtering by specific IP address group name
    and accepts pipeline input from Get-SqlDscServerProtocol.
  • SqlResourceBase
    • Added Protocol property to specify the network protocol (tcp, np, lpc)
      when connecting to SQL Server instances
      (issue #2041).
    • Added Port property to specify the TCP port number when connecting to SQL
      Server instances
      (issue #2041).
  • Connect-SqlDscDatabaseEngine
    • Added Protocol parameter to specify the network protocol when connecting.
    • Added Port parameter to specify the TCP port number when connecting.
      Connection strings now support the format [protocol:]hostname[\instance][,port].

This Pull Request (PR) fixes the following issues

Task list

  • Added an entry to the change log under the Unreleased section of the
    file CHANGELOG.md. Entry should say what was changed and how that
    affects users (if applicable), and reference the issue being resolved
    (if applicable).
  • Resource documentation updated in the resource's README.md.
  • Resource parameter descriptions updated in schema.mof.
  • Comment-based help updated, including parameter descriptions.
  • Localization strings updated.
  • Examples updated.
  • Unit tests updated. See DSC Community Testing Guidelines.
  • Integration tests updated (where possible). See DSC Community Testing Guidelines.
  • Code changes adheres to DSC Community Style Guidelines.

This change is Reviewable

@johlju johlju requested a review from a team as a code owner December 28, 2025 09:55
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 28, 2025

Walkthrough

Adds TCP/IP discovery and connection controls: new Get-SqlDscServerProtocolTcpIp command; Protocol and Port properties/parameters on SqlResourceBase, Connect‑SqlDscDatabaseEngine and Connect‑SQL; ExcludeDscProperties append changes; SMO test-stub refactor; unit/integration tests and localization strings.

Changes

Cohort / File(s) Summary
New TCP/IP command
source/Public/Get-SqlDscServerProtocolTcpIp.ps1
New exported function with two parameter sets (ByServerName, ByServerProtocolObject) returning SMO ServerIPAddress objects for TCP/IP address groups; validates protocol is TCP and errors on missing groups.
Connection surface
source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psm1, source/Public/Connect-SqlDscDatabaseEngine.ps1
Added Protocol (ValidateSet: tcp,np,lpc) and Port (UInt16) parameters; connection instance string assembly now supports protocol: prefix and ,port suffix and passes them into SMO/Connect logic.
Resource base
source/Classes/011.SqlResourceBase.ps1
Added public Protocol (string) and Port (nullable UInt16) properties; GetServerObject() forwards these into Connect‑SqlDscDatabaseEngine when set.
ExcludeDscProperties adjustments
source/Classes/020.SqlAgentAlert.ps1, source/Classes/020.SqlAudit.ps1, source/Classes/020.SqlDatabasePermission.ps1, source/Classes/020.SqlPermission.ps1
Constructors changed to append to ExcludeDscProperties instead of overwriting it, altering which properties are excluded by each class.
SMO test stubs
tests/Unit/Stubs/SMO.cs
IPAddressPropertyCollection and ServerIPAddressCollection now implement IEnumerable, use dictionary-backed storage, expose indexers and GetEnumerator(); removed legacy Item properties and setter-based Count.
Unit tests
tests/Unit/Public/Get-SqlDscServerProtocolTcpIp.Tests.ps1, tests/Unit/Public/Connect-SqlDscDatabaseEngine.Tests.ps1, tests/Unit/SqlServerDsc.Common.Tests.ps1, tests/Unit/Classes/SqlResourceBase.Tests.ps1
New/updated tests covering Get‑SqlDscServerProtocolTcpIp parameter sets, error paths, pipeline input, and Connect‑SQL/Connect‑SqlDscDatabaseEngine Protocol/Port formatting and propagation.
Integration tests & CI
tests/Integration/Commands/Get-SqlDscServerProtocolTcpIp.Integration.Tests.ps1, tests/Integration/Commands/Connect-SqlDscDatabaseEngine.Integration.Tests.ps1, azure-pipelines.yml
Added integration tests for TCP/IP discovery and connection scenarios; pipeline updated to include the new integration test.
Localization & changelog
source/en-US/SqlServerDsc.strings.psd1, CHANGELOG.md
Added localization strings for TCP/IP retrieval and errors; changelog updated to document new command and connection properties.

Sequence Diagram(s)

%%{init: {"themeVariables":{"actorBorder":"#1f618d","actorBackground":"#eaf3fb","sequenceNoteBackground":"#f6f9ff"}}}%%
sequenceDiagram
  autonumber
  actor Caller as Client / Cmdlet
  participant GetCmd as Get-SqlDscServerProtocolTcpIp
  participant ConnectCmd as Connect-SqlDscDatabaseEngine / Connect-SQL
  participant SMO as SMO WMI/SMO
  participant SQL as SQL Server Instance

  rect rgb(240,248,255)
  Caller->>GetCmd: Request IP groups (Server/Instance or ServerProtocol)
  GetCmd->>SMO: Query ServerProtocol (Tcp) & ServerIPAddress collection
  SMO-->>GetCmd: Return ServerProtocol / IPAddress objects
  GetCmd-->>Caller: Return IPAddress object(s)
  end

  rect rgb(255,250,240)
  Caller->>ConnectCmd: Connect with ServerName/Instance, Protocol?, Port?
  ConnectCmd->>SMO: Build ServerInstance (protocol:server[,port]) and New-Object Server
  SMO->>SQL: Open connection using formatted ServerInstance
  SQL-->>SMO: Connection result (success/fail)
  SMO-->>ConnectCmd: Connected Server object / status
  ConnectCmd-->>Caller: Return server object or throw
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% 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 PR title 'SqlServerBase: Support connection protocol and port' directly summarizes the main change—adding Protocol and Port support to SqlResourceBase and related components for SQL Server connection configuration.
Description check ✅ Passed The PR description is directly related to the changeset, detailing the new Get-SqlDscServerProtocolTcpIp command, Protocol and Port properties added to SqlResourceBase, and Protocol/Port parameters added to Connect-SqlDscDatabaseEngine.
Linked Issues check ✅ Passed All code changes directly fulfill issue #2041's objective: exposing connection options (Protocol and Port) to allow DSC resources to successfully connect in environments where default connection attempts fail by constructing custom connection strings.
Out of Scope Changes check ✅ Passed All changes are in scope: Get-SqlDscServerProtocolTcpIp retrieves TCP/IP info, Protocol/Port properties and parameters enable protocol/port specification, ExcludeDscProperties refactoring supports base class extensibility, and SMO stubs enable test support for the new functionality.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Comment thread source/Public/Get-SqlDscServerProtocolTcpIp.ps1 Fixed
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 (7)
tests/Unit/Public/Connect-SqlDscDatabaseEngine.Tests.ps1 (1)

54-64: Unit tests correctly cover new Protocol/Port parameters

Updating the parameter‑set expectations and adding explicit pass‑through tests for Protocol and Port into Connect-Sql gives solid coverage of the new behavior and aligns with the unit-test guidelines for public commands. I don’t see any issues here.

If you want slightly broader coverage later, you could add one more It verifying Protocol/Port flow when Credential is used (SqlServerWithCredential parameter set), but this is not required based on the current implementation.

Also applies to: 115-163

source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psm1 (1)

371-378: Connection string assembly is correct; consider tightening Port validation

The new Protocol/Port handling builds connection strings exactly as documented ([protocol:]hostname[\instance][,port]) for both default and named instances, which should address scenarios needing explicit protocol/port.

To harden input a bit, you could:

  • Prevent obviously invalid TCP ports (e.g. 0) via ValidateRange.
  • Optionally document (or enforce) that Port is intended for TCP usage.

For example, just to guard the range:

Suggested validation for Port
-        [Parameter()]
-        [System.UInt16]
-        $Port,
+        [Parameter()]
+        [ValidateRange(1, 65535)]
+        [System.UInt16]
+        $Port,

This keeps the existing behavior but avoids silently accepting invalid port values.

Also applies to: 392-403, 413-423

tests/Unit/SqlServerDsc.Common.Tests.ps1 (1)

2559-2668: Protocol/Port connection string tests are solid; duplication could be reduced

The new Protocol/Port contexts exercise exactly the new formatting (tcp:..., ...,port, and tcp:...\...,port) and keep the New-Object mocks minimal yet sufficient, which is a good fit for these cases.

If you want to trim a bit of duplication later, you could extract the shared minimal New-Object stub into a helper or reuse the existing $mockNewObject_MicrosoftDatabaseEngine pattern with a configurable expectation, but that’s purely cosmetic.

tests/Integration/Commands/Get-SqlDscServerProtocolTcpIp.Integration.Tests.ps1 (1)

1-145: Integration coverage for Get-SqlDscServerProtocolTcpIp looks good; consider CI env flag

The test file follows the standard integration setup (BeforeDiscovery + module import), avoids mocking, and exercises both parameter sets plus TCP port retrieval from IPAll, which is appropriate for this command.

If you want to align even more with the broader test conventions, you could set $env:SqlServerDscCI = $true in BeforeAll and clear it in an AfterAll block so other tooling can reliably detect CI integration runs, but that’s optional and not required for correctness.

tests/Unit/Public/Get-SqlDscServerProtocolTcpIp.Tests.ps1 (1)

335-343: Consider using more explicit parameter attribute assertions.

The assertions for optional parameters and pipeline parameters use indirect patterns. While functional, consider more explicit checks:

🔎 Suggested improvements
        It 'Should have IpAddressGroup as an optional parameter' {
            $parameterInfo = (Get-Command -Name 'Get-SqlDscServerProtocolTcpIp').Parameters['IpAddressGroup']
-           $parameterInfo.Attributes.Mandatory | Should -BeFalse
+           $mandatoryAttribute = $parameterInfo.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }
+           $mandatoryAttribute.Mandatory | Should -BeFalse
        }

        It 'Should have ServerProtocolObject as a pipeline parameter' {
            $parameterInfo = (Get-Command -Name 'Get-SqlDscServerProtocolTcpIp').Parameters['ServerProtocolObject']
-           $parameterInfo.Attributes.ValueFromPipeline | Should -Not -Contain $false
+           $pipelineAttribute = $parameterInfo.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }
+           $pipelineAttribute.ValueFromPipeline | Should -BeTrue
        }
source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (2)

107-169: Consider using try/finally for ErrorActionPreference restoration.

The current pattern restores $ErrorActionPreference at multiple exit points (lines 142, 176, 202), but if Get-SqlDscServerProtocol at line 135 throws an exception, the original $ErrorActionPreference won't be restored. While the guidelines suggest avoiding try-catch-finally for -ErrorAction 'Stop' commands, this is specifically for the pattern of setting/restoring around a single call. For functions with multiple exit paths and potential errors, consider a try/finally wrapper for guaranteed cleanup.


192-210: Consider simplifying collection enumeration.

The foreach loop with array concatenation works but could be simplified. Since serverProtocol.IPAddresses is now enumerable (per SMO.cs changes), you could use pipeline-based collection.

🔎 Simplified approach
        else
        {
            # Get all IP address groups
-           $allIpAddresses = @()
-
-           foreach ($ipAddress in $serverProtocol.IPAddresses)
-           {
-               $allIpAddresses += $ipAddress
-           }
+           $allIpAddresses = @($serverProtocol.IPAddresses)

            $ErrorActionPreference = $previousErrorActionPreference

            if ($allIpAddresses.Count -eq 0)
            {
                return $null
            }

            return $allIpAddresses
        }

…s items instead of null when no addresses are found
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: 1

🧹 Nitpick comments (2)
source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (2)

109-116: Consider following the ErrorActionPreference guideline pattern.

The current code sets $ErrorActionPreference = 'Stop' for the entire process block (line 110), then uses -ErrorAction 'Stop' on specific commands (lines 115, 135). The -ErrorAction 'Stop' parameters are redundant when ErrorActionPreference is already 'Stop'.

Per coding guidelines, the recommended pattern is to set $ErrorActionPreference = 'Stop' immediately before a command, execute it, then restore the previous value directly after—rather than setting it for the entire block. This makes the error-handling scope more explicit and easier to maintain.

Example of guideline pattern
# For line 115
$previousErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
$ServerName = Get-ComputerName
$ErrorActionPreference = $previousErrorActionPreference

This pattern can be repeated for each command that needs Stop behavior.

As per coding guidelines.

Also applies to: 135-136


195-207: Consider simplifying by outputting items directly.

The code builds an intermediate array $allIpAddresses (lines 195-200) and then iterates over it to output items (lines 204-207). This can be simplified by outputting items directly during enumeration, eliminating the intermediate array and avoiding the performance overhead of array concatenation in a loop.

🔎 Proposed simplification
-        # Get all IP address groups
-        $allIpAddresses = @()
-
-        foreach ($ipAddress in $serverProtocol.IPAddresses)
-        {
-            $allIpAddresses += $ipAddress
-        }
-
         $ErrorActionPreference = $previousErrorActionPreference
 
-        foreach ($ipAddressItem in $allIpAddresses)
+        # Get all IP address groups
+        foreach ($ipAddress in $serverProtocol.IPAddresses)
         {
-            $ipAddressItem
+            $ipAddress
         }

This approach maintains the same behavior (returns $null when no addresses exist, outputs each address individually) while reducing complexity.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a0aa28a and f2d41f8.

📒 Files selected for processing (1)
  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
🧰 Additional context used
📓 Path-based instructions (6)
**/*.ps1

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

**/*.ps1: Format public commands as {Verb}-SqlDsc{Noun} following PowerShell naming conventions
Format private functions as {Verb}-{Noun} following PowerShell naming conventions

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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 in PowerShell scripts
Use localized string keys from $script:localizedData, not hardcoded strings, in diagnostic messages
Reference localized strings using the syntax: Write-Verbose -Message ($script:localizedData.KeyName -f $value1)

Localize all strings using string keys; remove any orphaned string keys

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
source/Public/*.ps1

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

Public commands should be located in source/Public/{CommandName}.ps1

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
**/*.{ps1,psm1,psd1}

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

**/*.{ps1,psm1,psd1}: Use descriptive names (3+ characters, no abbreviations) for functions, parameters, variables, and classes
Functions: Use PascalCase with Verb-Noun format using approved verbs
Parameters: Use PascalCase naming
Variables: Use camelCase naming
Keywords: Use lower-case
Classes: Use PascalCase naming
Include scope for script/global/environment variables: $script:, $global:, $env:
Use 4 spaces for indentation (no tabs)
Use one space around operators: $a = 1 + 2
Use one space between type and variable: [String] $name
Use one space between keyword and parenthesis: if ($condition)
No spaces on empty lines
Limit lines to 120 characters
Place newline before opening brace (except variable assignments)
Place one newline after opening brace
Place two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed: 'text' vs "text $variable"
For single-line arrays use: @('one', 'two', 'three')
For multi-line arrays: place each element on separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
For empty hashtables use: @{}
For hashtables: place each property on separate line with proper indentation and use PascalCase for property names
Single-line comments: use # Comment format (capitalized, on own line)
Multi-line comments: use <# Comment #> format (opening and closing brackets on own line with indented text)
No commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples in comment-based help for all parameter sets and combinations
INPUTS section in comment-based help: List each pipeline-accepted type as inline code with a 1-line description, repeat keyword for each input type, specify None. if there are no inp...

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.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 as inline code with a 1‑line description...

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
🧠 Learnings (8)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`
📚 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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-08-16T13:35:08.323Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: source/Public/Get-SqlDscLogin.ps1:0-0
Timestamp: 2025-08-16T13:35:08.323Z
Learning: In PowerShell, users expect to receive $null when no objects are found or when a non-terminating error occurs, rather than empty arrays. This is normal PowerShell behavior and should be maintained in DSC commands.

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:58:20.404Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-11-27T17:58:20.404Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : DSC class-based resources must use `[Nullable[{FullTypeName}]]` syntax for value-type properties (e.g., `[Nullable[System.Int32]]`)

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `[OutputType({return type})]` for functions with output, use `[OutputType()]` for functions with no output

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Do not use the unary comma operator (`,`) in return statements to force an array

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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 (2)
source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (2)

1-78: LGTM: Well-structured comment-based help.

The comment-based help follows all guidelines with comprehensive documentation including SYNOPSIS, DESCRIPTION, multiple EXAMPLES, INPUTS, OUTPUTS, and NOTES sections. The OUTPUTS section correctly specifies the single return type, and the NOTES section appropriately documents the IPAddressProperties collection structure.


79-105: LGTM: Function declaration and parameters follow guidelines.

The function declaration correctly uses the Get-SqlDsc{Noun} naming pattern, includes proper attributes, and all parameters are well-structured with appropriate types and parameter set assignments. Pipeline support for ServerProtocolObject is correctly implemented.

Comment thread source/Public/Get-SqlDscServerProtocolTcpIp.ps1 Outdated
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: 1

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2d41f8 and cdbcf50.

📒 Files selected for processing (2)
  • source/Public/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
🧰 Additional context used
📓 Path-based instructions (6)
**/*.ps1

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

**/*.ps1: Format public commands as {Verb}-SqlDsc{Noun} following PowerShell naming conventions
Format private functions as {Verb}-{Noun} following PowerShell naming conventions

Files:

  • source/Public/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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 in PowerShell scripts
Use localized string keys from $script:localizedData, not hardcoded strings, in diagnostic messages
Reference localized strings using the syntax: Write-Verbose -Message ($script:localizedData.KeyName -f $value1)

Localize all strings using string keys; remove any orphaned string keys

Files:

  • source/Public/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
source/Public/*.ps1

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

Public commands should be located in source/Public/{CommandName}.ps1

Files:

  • source/Public/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
**/*.{ps1,psm1,psd1}

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

**/*.{ps1,psm1,psd1}: Use descriptive names (3+ characters, no abbreviations) for functions, parameters, variables, and classes
Functions: Use PascalCase with Verb-Noun format using approved verbs
Parameters: Use PascalCase naming
Variables: Use camelCase naming
Keywords: Use lower-case
Classes: Use PascalCase naming
Include scope for script/global/environment variables: $script:, $global:, $env:
Use 4 spaces for indentation (no tabs)
Use one space around operators: $a = 1 + 2
Use one space between type and variable: [String] $name
Use one space between keyword and parenthesis: if ($condition)
No spaces on empty lines
Limit lines to 120 characters
Place newline before opening brace (except variable assignments)
Place one newline after opening brace
Place two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed: 'text' vs "text $variable"
For single-line arrays use: @('one', 'two', 'three')
For multi-line arrays: place each element on separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
For empty hashtables use: @{}
For hashtables: place each property on separate line with proper indentation and use PascalCase for property names
Single-line comments: use # Comment format (capitalized, on own line)
Multi-line comments: use <# Comment #> format (opening and closing brackets on own line with indented text)
No commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples in comment-based help for all parameter sets and combinations
INPUTS section in comment-based help: List each pipeline-accepted type as inline code with a 1-line description, repeat keyword for each input type, specify None. if there are no inp...

Files:

  • source/Public/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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 as inline code with a 1‑line description...

Files:

  • source/Public/Connect-SqlDscDatabaseEngine.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
🧠 Learnings (20)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/resources/**/*.ps1 : Add `InstanceName`, `ServerName`, and `Credential` to `$this.ExcludeDscProperties` in Database Engine resources
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`

Applied to files:

  • source/Public/Connect-SqlDscDatabaseEngine.ps1
📚 Learning: 2025-10-19T10:33:22.772Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2309
File: tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1:132-148
Timestamp: 2025-10-19T10:33:22.772Z
Learning: In SqlServerDsc integration tests, when connecting via Connect-SqlDscDatabaseEngine using a local Windows account (e.g., 'SqlAdmin'), use the plain username format without computer/domain prefix. This is Windows Authentication with a local account. The NetBIOS format (e.g., 'COMPUTER\SqlAdmin') is only used for SqlSysAdminAccounts during SQL Server setup/rebuild and will throw an exception if used with Connect-SqlDscDatabaseEngine for local Windows accounts.

Applied to files:

  • source/Public/Connect-SqlDscDatabaseEngine.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-08-16T13:35:08.323Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: source/Public/Get-SqlDscLogin.ps1:0-0
Timestamp: 2025-08-16T13:35:08.323Z
Learning: In PowerShell, users expect to receive $null when no objects are found or when a non-terminating error occurs, rather than empty arrays. This is normal PowerShell behavior and should be maintained in DSC commands.

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:58:20.404Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-11-27T17:58:20.404Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : DSC class-based resources must use `[Nullable[{FullTypeName}]]` syntax for value-type properties (e.g., `[Nullable[System.Int32]]`)

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `[OutputType({return type})]` for functions with output, use `[OutputType()]` for functions with no output

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Do not use the unary comma operator (`,`) in return statements to force an array

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : For error handling, use `New-ErrorRecord` instead of `[System.Management.Automation.ErrorRecord]::new(...)`

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : For error handling, use `New-Exception` instead of `[System.Exception]::new(...)`

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-08-17T18:25:52.891Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2132
File: source/Public/New-SqlDscLogin.ps1:218-225
Timestamp: 2025-08-17T18:25:52.891Z
Learning: PowerShell's System.Management.Automation.ErrorRecord constructor accepts a string as the first parameter and automatically converts it to an exception object internally. No need to manually wrap strings in System.Exception when creating ErrorRecord objects in PowerShell.

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-ArgumentException` for argument-related errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-InvalidDataException` for invalid data errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:58:20.404Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-11-27T17:58:20.404Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : DSC class-based resources must use `New-*Exception` commands (such as `New-InvalidDataException`, `New-ArgumentException`, `New-InvalidOperationException`, `New-ObjectNotFoundException`, `New-InvalidResultException`, `New-NotImplementedException`) instead of `throw` for terminating errors in classes

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-InvalidOperationException` for invalid operation errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `Write-Error` for non-terminating errors with `-Message` (localized string), `-Category` (relevant error category), `-ErrorId` (unique ID), and `-TargetObject` (object causing error)

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-NotImplementedException` for not implemented errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-InvalidResultException` for invalid result errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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 (4)
source/Public/Connect-SqlDscDatabaseEngine.ps1 (1)

31-47: LGTM! Protocol and Port parameters are well-implemented.

The new parameters are properly validated, documented, and integrated. The ValidateSet for Protocol and ValidateRange for Port ensure correct input values. The documentation clearly explains usage, including the lowercase protocol convention and connection string format examples.

Also applies to: 79-101, 133-141

source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (3)

158-158: Good use of New-ErrorRecord helper.

The code correctly uses New-ErrorRecord instead of direct ErrorRecord instantiation. This aligns with coding guidelines and resolves the concern from the previous review.

Also applies to: 194-194


1-78: Comment-based help is comprehensive and well-structured.

The documentation includes all required sections (SYNOPSIS, DESCRIPTION, PARAMETER, EXAMPLE, INPUTS, OUTPUTS, NOTES) with appropriate detail. The examples cover multiple scenarios, and the NOTES section provides critical information about the returned object's properties.


197-197: Return pattern correctly handles single and multiple objects.

The function returns a single ServerIPAddress when IpAddressGroup is specified (line 197) or iterates through all IP addresses when not specified (lines 202-205). This pattern correctly avoids the unary comma operator and allows PowerShell to handle array unwrapping naturally.

Also applies to: 202-205

Comment thread source/Public/Get-SqlDscServerProtocolTcpIp.ps1 Outdated
@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 28, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (82bd423) to head (7285034).
⚠️ Report is 39 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@          Coverage Diff          @@
##            main   #2382   +/-   ##
=====================================
  Coverage     94%     94%           
=====================================
  Files        173     174    +1     
  Lines      10048   10095   +47     
=====================================
+ Hits        9474    9521   +47     
  Misses       574     574           
Flag Coverage Δ
unit 94% <100%> (+<1%) ⬆️
Files with missing lines Coverage Δ
source/Classes/011.SqlResourceBase.ps1 95% <100%> (+4%) ⬆️
source/Classes/020.SqlAgentAlert.ps1 100% <100%> (ø)
source/Classes/020.SqlAudit.ps1 100% <100%> (ø)
source/Classes/020.SqlDatabasePermission.ps1 100% <100%> (ø)
source/Classes/020.SqlPermission.ps1 100% <100%> (ø)
...dules/SqlServerDsc.Common/SqlServerDsc.Common.psm1 96% <100%> (+<1%) ⬆️
source/Public/Connect-SqlDscDatabaseEngine.ps1 100% <ø> (ø)
source/Public/Get-SqlDscServerProtocolTcpIp.ps1 100% <100%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…tests for Protocol and Port properties in SqlResourceBase
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

♻️ Duplicate comments (2)
source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (2)

79-105: Function declaration and parameters look good.

The parameter sets, attributes, and OutputType declaration follow PowerShell and DSC Community guidelines correctly. The OutputType declares the individual object type (ServerIPAddress) rather than an array type, which is correct per PowerShell conventions—the function outputs individual objects to the pipeline, even when multiple objects are returned.

The static analysis warning about System.Object[] appears to be a false positive resulting from the tool detecting multiple pipeline outputs.


147-159: Error handling correctly uses helper functions.

The error handling has been properly updated to use the helper functions (New-ArgumentException, New-InvalidOperationException, and New-ErrorRecord) as recommended in past review comments. The pattern follows guidelines:

  • Uses specific exception helpers with -PassThru
  • Wraps with New-ErrorRecord including ErrorId, ErrorCategory, and TargetObject
  • Calls $PSCmdlet.ThrowTerminatingError() for terminating errors
  • All messages use localized strings from $script:localizedData

Also applies to: 183-195

🧹 Nitpick comments (3)
tests/Unit/Classes/SqlResourceBase.Tests.ps1 (2)

125-143: LGTM! Protocol property test follows established pattern.

The test correctly verifies that the Protocol property is passed to Connect-SqlDscDatabaseEngine. The structure and approach are consistent with the existing Credential test.

Optional: Verify the actual parameter value for more thorough testing

The current parameter filter only checks if the Protocol key exists, not the actual value. Consider verifying the exact value being passed:

                Should -Invoke -CommandName Connect-SqlDscDatabaseEngine -ParameterFilter {
-                    $PesterBoundParameters.Keys -contains 'Protocol'
+                    $Protocol -eq 'tcp'
                } -Exactly -Times 1 -Scope It

This would ensure that not only is the parameter passed, but it has the correct value.


145-163: LGTM! Port property test follows established pattern.

The test correctly verifies that the Port property is passed to Connect-SqlDscDatabaseEngine. The structure and approach are consistent with the Protocol and Credential tests.

Optional: Consider adding a combined scenario test

The current tests verify Protocol and Port independently. Consider adding a test that verifies both properties work together:

Context 'When properties Protocol and Port are used together' {
    BeforeAll {
        $mockSqlResourceBaseInstance = InModuleScope -ScriptBlock {
            [SqlResourceBase]::new()
        }

        $mockSqlResourceBaseInstance.Protocol = 'tcp'
        $mockSqlResourceBaseInstance.Port = 1433
    }

    It 'Should call the correct mock with both parameters' {
        $result = $mockSqlResourceBaseInstance.GetServerObject()

        $result | Should -BeOfType 'Microsoft.SqlServer.Management.Smo.Server'

        Should -Invoke -CommandName Connect-SqlDscDatabaseEngine -ParameterFilter {
            $Protocol -eq 'tcp' -and $Port -eq 1433
        } -Exactly -Times 1 -Scope It
    }
}

This would ensure the implementation correctly handles multiple connection parameters simultaneously.

source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (1)

72-77: Consider condensing the .NOTES section.

The .NOTES section contains detailed property descriptions that exceed the guideline recommendation of ≤2 short sentences. Consider moving this structural information to the DESCRIPTION section or adding a dedicated example showing property access.

🔎 Example condensed .NOTES and enhanced .DESCRIPTION

Condensed .NOTES:

     .NOTES
-        The returned ServerIPAddress object's IPAddressProperties collection contains:
-        - TcpPort: The static TCP port number(s) as a comma-separated string
-        - TcpDynamicPorts: The dynamic port number (only for IPAll group)
-        - Enabled: Whether the IP address group is enabled
-        - Active: Whether the IP address is active
+        The ServerIPAddress object contains an IPAddressProperties collection with TcpPort, TcpDynamicPorts, Enabled, and Active properties.

Or move to DESCRIPTION:

     .DESCRIPTION
         Returns TCP/IP address group information for a SQL Server instance using
         SMO (SQL Server Management Objects). The command returns the IP address
         groups configured for the TCP/IP protocol, including their port configuration.

-        Each returned object contains an IPAddressProperties collection with
-        properties such as 'TcpPort', 'TcpDynamicPorts', 'Enabled', and 'Active'.
+        Each returned object contains an IPAddressProperties collection with properties:
+        - TcpPort: Static TCP port number(s) as comma-separated string
+        - TcpDynamicPorts: Dynamic port number (only for IPAll group)
+        - Enabled: Whether the IP address group is enabled
+        - Active: Whether the IP address is active

As per coding guidelines.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdbcf50 and 7285034.

📒 Files selected for processing (2)
  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
🧰 Additional context used
📓 Path-based instructions (10)
**/*.ps1

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

**/*.ps1: Format public commands as {Verb}-SqlDsc{Noun} following PowerShell naming conventions
Format private functions as {Verb}-{Noun} following PowerShell naming conventions

Files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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
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
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
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'
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
Spacing between blocks, arrange, act, and assert for readability
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 commands
Never use Mock inside InModuleScope-block
Never use param() inside -MockWith scriptblock...

Files:

  • tests/Unit/Classes/SqlResourceBase.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
  • Spacing between blocks, arrange, act, and assert for readability

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, `...

Files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
tests/Unit/Classes/*.[Tt]ests.ps1

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

Class resources: tests/Unit/Classes/{Name}.Tests.ps1

Files:

  • tests/Unit/Classes/SqlResourceBase.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: Test with localized strings using InModuleScope -ScriptBlock { $script:localizedData.Key }
Mock files using the $TestDrive variable (path to the test drive)
All public commands require parameter set validation tests
Use the exact setup block with BeforeDiscovery, BeforeAll, and AfterAll blocks including DscResource.Test module import and PSDefaultParameterValues configuration
Parameter set validation tests should use Get-Command with Where-Object filtering and Should assertions to verify ParameterSetName and ParameterListAsString
Parameter property tests should verify mandatory parameter attributes using Get-Command Parameters and Should -BeTrue assertions

Files:

  • tests/Unit/Classes/SqlResourceBase.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/Classes/SqlResourceBase.Tests.ps1
tests/Unit/**/*.Tests.ps1

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

Unit tests should be located in tests/Unit/{Classes|Public|Private}/{Name}.Tests.ps1

Files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
**/*.{ps1,psm1,psd1}

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

**/*.{ps1,psm1,psd1}: Use descriptive names (3+ characters, no abbreviations) for functions, parameters, variables, and classes
Functions: Use PascalCase with Verb-Noun format using approved verbs
Parameters: Use PascalCase naming
Variables: Use camelCase naming
Keywords: Use lower-case
Classes: Use PascalCase naming
Include scope for script/global/environment variables: $script:, $global:, $env:
Use 4 spaces for indentation (no tabs)
Use one space around operators: $a = 1 + 2
Use one space between type and variable: [String] $name
Use one space between keyword and parenthesis: if ($condition)
No spaces on empty lines
Limit lines to 120 characters
Place newline before opening brace (except variable assignments)
Place one newline after opening brace
Place two newlines after closing brace (one if followed by another brace or continuation)
Use single quotes unless variable expansion is needed: 'text' vs "text $variable"
For single-line arrays use: @('one', 'two', 'three')
For multi-line arrays: place each element on separate line with proper indentation
Do not use the unary comma operator (,) in return statements to force an array
For empty hashtables use: @{}
For hashtables: place each property on separate line with proper indentation and use PascalCase for property names
Single-line comments: use # Comment format (capitalized, on own line)
Multi-line comments: use <# Comment #> format (opening and closing brackets on own line with indented text)
No commented-out code
Always add comment-based help to all functions and scripts with SYNOPSIS, DESCRIPTION (40+ chars), PARAMETER, and EXAMPLE sections before function/class
Comment-based help indentation: keywords 4 spaces, text 8 spaces
Include examples in comment-based help for all parameter sets and combinations
INPUTS section in comment-based help: List each pipeline-accepted type as inline code with a 1-line description, repeat keyword for each input type, specify None. if there are no inp...

Files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Classes/SqlResourceBase.Tests.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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 as inline code with a 1‑line description...

Files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
  • source/Public/Get-SqlDscServerProtocolTcpIp.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 in PowerShell scripts
Use localized string keys from $script:localizedData, not hardcoded strings, in diagnostic messages
Reference localized strings using the syntax: Write-Verbose -Message ($script:localizedData.KeyName -f $value1)

Localize all strings using string keys; remove any orphaned string keys

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
source/Public/*.ps1

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

Public commands should be located in source/Public/{CommandName}.ps1

Files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
🧠 Learnings (36)
📓 Common learnings
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/resources/**/*.ps1 : Add `InstanceName`, `ServerName`, and `Credential` to `$this.ExcludeDscProperties` in Database Engine resources
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2309
File: tests/Integration/Commands/Initialize-SqlDscRebuildDatabase.Integration.Tests.ps1:132-148
Timestamp: 2025-10-19T10:33:22.772Z
Learning: In SqlServerDsc integration tests, when connecting via Connect-SqlDscDatabaseEngine using a local Windows account (e.g., 'SqlAdmin'), use the plain username format without computer/domain prefix. This is Windows Authentication with a local account. The NetBIOS format (e.g., 'COMPUTER\SqlAdmin') is only used for SqlSysAdminAccounts during SQL Server setup/rebuild and will throw an exception if used with Connect-SqlDscDatabaseEngine for local Windows accounts.
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/Integration/**/*.ps1 : Integration tests: use `Connect-SqlDscDatabaseEngine` for SQL Server DB session with correct CI credentials, and always follow with `Disconnect-SqlDscDatabaseEngine`

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : When unit tests test classes or commands containing SMO types like `[Microsoft.SqlServer.Management.Smo.*]`, ensure they are properly stubbed in SMO.cs

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : Add `$env:SqlServerDscCI = $true` in `BeforeAll` block and remove in `AfterAll` block of unit tests

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to tests/Unit/Classes/*.[Tt]ests.ps1 : Class resources: `tests/Unit/Classes/{Name}.Tests.ps1`

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/tests/**/*.tests.ps1 : In unit tests: use SMO stub types from SMO.cs, never mock SMO types

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.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/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: Applies to **/resources/**/*.ps1 : Database Engine resources must inherit from `SqlResourceBase`

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:58:02.422Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/SqlServerDsc-guidelines.instructions.md:0-0
Timestamp: 2025-11-27T17:58:02.422Z
Learning: After changing SMO stub types in SMO.cs, run tests in a new PowerShell session for changes to take effect

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : All public commands and class-based resources must have integration tests

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Cover all scenarios and code paths

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Mocking in `BeforeAll` (`BeforeEach` only when required)

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T18:56:46.759Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 1622
File: tests/Integration/DSC_SqlDatabase.Integration.Tests.ps1:1-30
Timestamp: 2025-11-27T18:56:46.759Z
Learning: Integration tests for MOF-based DSC resources (located in source/DSCResources/**) should use the Initialize-TestEnvironment pattern with -ResourceType 'Mof', not the BeforeDiscovery/BeforeAll pattern. The BeforeDiscovery/BeforeAll pattern is for class-based resources only.

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Mock` inside `InModuleScope`-block

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-10-10T14:01:42.703Z
Learnt from: dan-hughes
Repo: dsccommunity/UpdateServicesDsc PR: 86
File: tests/Unit/MSFT_UpdateServicesServer.Tests.ps1:6-45
Timestamp: 2025-10-10T14:01:42.703Z
Learning: For script-based (MOF) DSC resources in UpdateServicesDsc, unit tests should use Initialize-TestEnvironment with variables $script:dscModuleName and $script:dscResourceName, and set -ResourceType 'Mof'. This differs from class-based resource tests which use the simpler $script:moduleName template without Initialize-TestEnvironment.

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.ps1
📚 Learning: 2025-11-27T17:59:27.205Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-pester.instructions.md:0-0
Timestamp: 2025-11-27T17:59:27.205Z
Learning: Applies to **/*.[Tt]ests.ps1 : Never use `Assert-MockCalled`, use `Should -Invoke` instead

Applied to files:

  • tests/Unit/Classes/SqlResourceBase.Tests.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-08-16T13:35:08.323Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2134
File: source/Public/Get-SqlDscLogin.ps1:0-0
Timestamp: 2025-08-16T13:35:08.323Z
Learning: In PowerShell, users expect to receive $null when no objects are found or when a non-terminating error occurs, rather than empty arrays. This is normal PowerShell behavior and should be maintained in DSC commands.

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:58:20.404Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-11-27T17:58:20.404Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : DSC class-based resources must use `[Nullable[{FullTypeName}]]` syntax for value-type properties (e.g., `[Nullable[System.Int32]]`)

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `[OutputType({return type})]` for functions with output, use `[OutputType()]` for functions with no output

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Do not use the unary comma operator (`,`) in return statements to force an array

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : For error handling, use `New-ErrorRecord` instead of `[System.Management.Automation.ErrorRecord]::new(...)`

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : For error handling, use `New-Exception` instead of `[System.Exception]::new(...)`

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-08-17T18:25:52.891Z
Learnt from: johlju
Repo: dsccommunity/SqlServerDsc PR: 2132
File: source/Public/New-SqlDscLogin.ps1:218-225
Timestamp: 2025-08-17T18:25:52.891Z
Learning: PowerShell's System.Management.Automation.ErrorRecord constructor accepts a string as the first parameter and automatically converts it to an exception object internally. No need to manually wrap strings in System.Exception when creating ErrorRecord objects in PowerShell.

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-ArgumentException` for argument-related errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-InvalidDataException` for invalid data errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:58:20.404Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-class-resource.instructions.md:0-0
Timestamp: 2025-11-27T17:58:20.404Z
Learning: Applies to source/[cC]lasses/**/*.ps1 : DSC class-based resources must use `New-*Exception` commands (such as `New-InvalidDataException`, `New-ArgumentException`, `New-InvalidOperationException`, `New-ObjectNotFoundException`, `New-InvalidResultException`, `New-NotImplementedException`) instead of `throw` for terminating errors in classes

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-InvalidOperationException` for invalid operation errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `Write-Error` for non-terminating errors with `-Message` (localized string), `-Category` (relevant error category), `-ErrorId` (unique ID), and `-TargetObject` (object causing error)

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-NotImplementedException` for not implemented errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : Use `$PSCmdlet.ThrowTerminatingError()` for terminating errors (except for classes), use relevant error category, in try-catch include exception with localized message

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-InvalidResultException` for invalid result errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-12-24T18:09:36.232Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-powershell.instructions.md:0-0
Timestamp: 2025-12-24T18:09:36.232Z
Learning: Applies to **/*.{ps1,psm1,psd1} : For most .NET types, use the `::new()` static method instead of `New-Object`, e.g., `[System.DateTime]::new()`

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.ps1
📚 Learning: 2025-11-27T17:59:01.508Z
Learnt from: CR
Repo: dsccommunity/SqlServerDsc PR: 0
File: .github/instructions/dsc-community-style-guidelines-mof-resources.instructions.md:0-0
Timestamp: 2025-11-27T17:59:01.508Z
Learning: Applies to source/DSCResources/**/*.psm1 : Use `New-ObjectNotFoundException` for object not found errors instead of `throw` in MOF-based DSC resources

Applied to files:

  • source/Public/Get-SqlDscServerProtocolTcpIp.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 (1)
source/Public/Get-SqlDscServerProtocolTcpIp.ps1 (1)

107-207: Process block implementation follows best practices.

The logic correctly handles both parameter sets with proper:

  • ErrorActionPreference save/restore around potentially failing operations (lines 112-117, 137-142)
  • Localized verbose messages using $script:localizedData.*
  • Pipeline output using idiomatic PowerShell (line 204 outputs individual objects without explicit Write-Output)
  • Appropriate use of return for early exit (line 197)

The implicit pipeline output pattern at line 204 is correct—placing $ipAddress alone on a line outputs each object to the pipeline individually, which is the standard PowerShell approach for returning multiple objects.

Copy link
Copy Markdown
Member Author

@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 18 files and all commit messages, made 1 comment, and resolved 1 discussion.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on @johlju).

@johlju johlju merged commit 352435f into dsccommunity:main Dec 28, 2025
49 checks passed
@johlju johlju deleted the f/sqlresourcebase-protocol-and-port branch December 28, 2025 19:32
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.

Connect-SQL : Failed to connect to SQL instance

2 participants