Created
March 9, 2017 15:58
-
-
Save marrobi/a28256e43edc2f137bc2ff95a68afe13 to your computer and use it in GitHub Desktop.
Execute SQL on PostgreSQL
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
Param | |
( | |
[string]$ServerHostName, | |
[int]$ServerPort = 5432, | |
[string]$User, | |
[string]$Password, | |
[string]$DBName, | |
[string]$SQLFilePath = "", | |
[string]$SQLCmd = "" | |
) | |
# Load ODBC Driver | |
[Reflection.Assembly]::LoadFrom('C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Npgsql\v4.0_3.2.1.0__5d8b90d52f46fda7\Npgsql.dll ') > $null | |
# Function to execute command | |
function ExecuteSQL ($SQLCmd,$ConnectionString) | |
{ | |
$DBConn = New-Object Npgsql.NpgsqlConnection | |
$DBConn.ConnectionString = $ConnectionString; | |
$DBConn.Open(); | |
$DBCmd = $DBConn.CreateCommand(); | |
$DBCmd.CommandText = $SQLCmd | |
$DBCmd.ExecuteReader(); | |
$DBConn.Close(); | |
} | |
# set connection string | |
$ConnectionString = "Host=$ServerHostName;Database=$DBName;Username=$User;Password=$Password;Command Timeout=300;Keepalive=30" | |
# if a command sent | |
if($SQLCmd -ne ""){ | |
ExecuteSQL -SQLCmd $SQLCmd -ConnectionString $ConnectionString | |
# if a file path | |
}else{ | |
ExecuteSQL -SQLCmd (Get-Content ($SQLFilePath)) -ConnectionString $ConnectionString | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment