Functions/New-SqlConnection.ps1

<#
.SYNOPSIS
    Creates and opens a new SQL Server connection.
 
.DESCRIPTION
    The New-SqlConnection function creates a new SqlConnection object using the provided
    connection string and opens the connection. This function is useful for establishing
    database connections that can be reused across multiple operations.
 
.PARAMETER ConnectionString
    Specifies the connection string for the SQL Server database connection.
 
.OUTPUTS
    System.Data.SqlClient.SqlConnection
    Returns an open SqlConnection object.
 
.EXAMPLE
    $connectionString = "Server=localhost;Database=MyDB;Integrated Security=true;"
    $connection = New-SqlConnection -ConnectionString $connectionString
     
    Creates and opens a connection to MyDB on localhost using integrated security.
 
.EXAMPLE
    $connectionString = "Server=sql.example.com;Database=Production;User ID=appuser;Password=P@ssw0rd;"
    $connection = New-SqlConnection -ConnectionString $connectionString
    # Use the connection for operations...
    $connection.Close()
     
    Creates a connection using SQL Server authentication and closes it when done.
 
.NOTES
    The returned connection is already opened and ready for use.
    Remember to close and dispose of the connection when finished to prevent resource leaks.
    This function will throw an exception if the connection cannot be established.
#>

Function New-SqlConnection {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "", Justification = "This doesn't need process")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "", Justification = "Target Credentials is used in dynamic script")]
    [Cmdletbinding()]
    param(
        [Parameter(Mandatory = $true, HelpMessage = "SQL Server connection string")]
        [string] $ConnectionString
    )
    Write-Verbose "Getting New Sql Connection"

    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
   
    $SqlConnection.ConnectionString = $ConnectionString
    
    Write-Verbose "Opening connection"
    $SqlConnection.Open()

    return $SqlConnection
}