Skip to content

Instantly share code, notes, and snippets.

@marrobi
Created March 9, 2017 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marrobi/a28256e43edc2f137bc2ff95a68afe13 to your computer and use it in GitHub Desktop.
Save marrobi/a28256e43edc2f137bc2ff95a68afe13 to your computer and use it in GitHub Desktop.
Execute SQL on PostgreSQL
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