Skip to content

Commit 5bf7d35

Browse files
committed
Add the -Provider parameter to the New-SqlConnection cmdlet
1 parent 0b893b8 commit 5bf7d35

2 files changed

Lines changed: 21 additions & 6 deletions

File tree

src/Connection/New-Connection.ps1

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,19 @@ using namespace System.Diagnostics.CodeAnalysis
1010
The newly created database connection.
1111
#>
1212
function New-SqlConnection {
13-
[CmdletBinding()]
13+
[CmdletBinding(DefaultParameterSetName = "Type")]
1414
[OutputType([System.Data.IDbConnection])]
1515
[SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "")]
1616
param (
1717
# The type of connection class to instantiate.
18-
[Parameter(Mandatory, Position = 0)]
18+
[Parameter(Mandatory, ParameterSetName = "Type", Position = 0)]
1919
[Type] $Type,
2020

21+
# The name of an ADO.NET provider.
22+
[Parameter(Mandatory, ParameterSetName = "Provider", Position = 0)]
23+
[ValidateSet("Odbc", "OleDb", "SqlClient")]
24+
[string] $Provider,
25+
2126
# The connection string used to open the database.
2227
[Parameter(Mandatory, Position = 1, ValueFromPipeline)]
2328
[string] $ConnectionString,
@@ -27,7 +32,14 @@ function New-SqlConnection {
2732
)
2833

2934
process {
30-
$connection = [IDbConnection] [Activator]::CreateInstance($Type, $ConnectionString)
35+
$class = switch ($Provider) {
36+
"Odbc" { [Odbc.OdbcConnection]; break }
37+
"OleDb" { [OleDb.OleDbConnection]; break }
38+
"SqlClient" { [SqlClient.SqlConnection]; break }
39+
default { $Type }
40+
}
41+
42+
$connection = [IDbConnection] [Activator]::CreateInstance($class, $ConnectionString)
3143
if ($Open) { $connection.Open() }
3244
$connection
3345
}

test/Connection/New-Connection.Tests.ps1

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@ using module ../../Sql.psd1
77
Tests the features of the `New-Connection` cmdlet.
88
#>
99
Describe "New-Connection" {
10-
It "should create a connection of the specified type" {
11-
$connection = New-SqlConnection ([System.Data.SQLite.SQLiteConnection]) "DataSource=:memory:"
12-
$connection | Should -BeOfType ([System.Data.SQLite.SQLiteConnection])
10+
It "should create a connection of the specified type" -ForEach @(
11+
@{ Provider = [System.Data.SQLite.SQLiteConnection]; ConnectionString = "DataSource=:memory:"; Expected = [System.Data.SQLite.SQLiteConnection] }
12+
@{ Provider = "SqlClient"; ConnectionString = "Server=localhost; Database=TestDb; Uid=user; Pwd=password"; Expected = [System.Data.SqlClient.SqlConnection] }
13+
) {
14+
$connection = New-SqlConnection $provider $connectionString
15+
$connection | Should -BeOfType $expected
1316
$connection.State | Should -Be ([ConnectionState]::Closed)
1417
$connection.Dispose()
1518
}

0 commit comments

Comments
 (0)