Created
January 30, 2015 13:02
-
-
Save gravejester/2bcf9378812b58c4c772 to your computer and use it in GitHub Desktop.
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment