forked from ahmetrende/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Get-PgOdbcData.ps1
60 lines (49 loc) · 1.72 KB
/
Get-PgOdbcData.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<#PSScriptInfo
.SYNOPSIS
Returns query result from PostgreSQL with ODBC.
.DESCRIPTION
This function returns a query result with PostgreSQL ODBC driver.
You can download odbc driver from https://odbc.postgresql.org
.EXAMPLE
Get-PgOdbcData -Servername "server1" -Database "postgres" -Query "SELECT now() as datetime;" -UserName "<UserName>" -Password "<Password>" -Port 5432
.NOTES
Version : 1.0 (2020-08-04)
File Name : Get-PgOdbcData.ps1
Author : Ahmet Rende ([email protected])
GitHub : https://github.com/ahmetrende
#>
function Get-PgOdbcData {
[CmdletBinding()]
param (
$Servername
,$Database
,$Query
,$UserName
,$Password
,$Port = 5432
,$DriverName = "PostgreSQL Unicode(x64)"
)
$ErrorActionPreference = 'Stop'
$OdbcName = "PG_" + (Get-Date -Format "FileDateTime") + "_" + $pid
Add-OdbcDsn -Name $OdbcName -DriverName $DriverName -DsnType User -SetPropertyValue @("Servername=$Servername", "Database=$Database", "Username=$UserName", "Password=$Password", "Port=$Port", "MaxLongVarcharSize=-4", "BoolsAsChar=0" ) > $null
$Conn = New-Object System.Data.Odbc.OdbcConnection
$Conn.ConnectionString = "DSN=$OdbcName;"
$Conn.Open()
$Cmd = New-object System.Data.Odbc.OdbcCommand($Query,$Conn)
$Dt = New-Object System.Data.DataTable
$Reader = $Cmd.ExecuteReader()
try {
$Dt.Load($Reader)
}
catch {
if ($_.Exception.Message -notlike "*Failed to enable constraints*"){
throw $_
}
}
finally{
$Conn.Dispose()
$Conn.Close()
Remove-OdbcDsn -Name $OdbcName -DsnType User > $null
}
$Dt
}