This function will let you create a database connection object for connecting to a database using ODBC.
It supports using DSN as well as setting up a DSN-less connection, and will return a database connection object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function New-OdbcConnection { | |
<# | |
.SYNPSIS | |
Create a new ODBC connection. | |
.DESCRIPTION | |
This function will create a new ODBC connection and return a database connection object. | |
.EXAMPLE | |
New-OdbcConnection -Dsn 'myDsn' | |
Create a new ODBC connection using the 'myDsn' DSN. | |
.EXAMPLE | |
New-OdbcConnection -Driver 'PostgreSQL ANSI' -Server 'server01' -Port '2725' -Database 'myDb' -Credential 'myUser' | |
Create a new DSN-less ODBC connection to a PostgreSQL database running on 'server01'. | |
.NOTES | |
Author: Øyvind Kallstad | |
Date: 30.01.2015 | |
Version: 1.0 | |
#> | |
[CmdletBinding(DefaultParameterSetName = 'Dsn')] | |
param ( | |
[Parameter(ParameterSetName = 'Dsn', Position = 0, Mandatory)] | |
[string] $Dsn, | |
[Parameter(ParameterSetName = 'DsnLess', Mandatory)] | |
[string] $Driver, | |
[Parameter(ParameterSetName = 'DsnLess', Mandatory)] | |
[string] $Server, | |
[Parameter(ParameterSetName = 'DsnLess', Mandatory)] | |
[string] $Port, | |
[Parameter(ParameterSetName = 'DsnLess', Mandatory)] | |
[string] $Database, | |
[Parameter()] | |
[System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty | |
) | |
if ($Dsn) { | |
$connectionString = "Dsn=$($Dsn)" | |
} | |
else { | |
$connectionString = "Driver={$($Driver)};Server=$($Server);Port=$($Port);Database=$($Database)" | |
} | |
if ($PSBoundParameters['Credential']) { | |
$connectionString += ";Uid=$($Credential.Username);Pwd=$($Credential.GetNetworkCredential().Password)" | |
} | |
try { | |
$odbcConnection = New-Object –TypeName 'System.Data.Odbc.OdbcConnection' –ArgumentList $connectionString | |
$odbcConnection.Open() | |
Write-Output $odbcConnection | |
} | |
catch { | |
Write-Warning $_.Exception.Message | |
} | |
} |