Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
function New-OdbcConnection {
Create a new ODBC connection.
This function will create a new ODBC connection and return a database connection object.
New-OdbcConnection -Dsn 'myDsn'
Create a new ODBC connection using the 'myDsn' DSN.
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'.
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,
[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
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