Connect to remote PostgreSql database using Powershell

Consult: https://odbc.postgresql.org/
Download: https://www.postgresql.org/ftp/odbc/versions/msi/

Data sources (ODBC) on Windows: Start → Search → odbc → User DSN → Add/Configure

Screenshot ODBC Driver Setup

Example :

$MyServer = "<ip>"
$MyPort  = "5432"
$MyDB = "<database>"
$MyUid = "<user>"
$MyPass = "<pass>"

$DBConnectionString = "Driver={PostgreSQL UNICODE(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
$DBCmd = $DBConn.CreateCommand();
$DBCmd.CommandText = "SELECT * FROM tb_module;";
$DBCmd.ExecuteReader();
$DBConn.Close();

Check if the DSN exists in ODBC data source. If not you have to create one going to 'Control Panel', 'Admin. Tools', 'Data Sources (ODBC)'. Then select 'Add User DSN'- Select the PostgreSQL driver, and fill in your server and database details. Test connection to check is all ok!


You actually have a typo in your connection string after Driver declaration. There is a double colon instead of a semicolon :)

Wrong:

{PostgreSQL UNICODE} : Server

Correct:

{PostgreSQL UNICODE} ; Server