New-OdbcConnection

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.

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s