Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment