2

I managed to connect to a PostgreSQL database via PowerShell after ages of trying.

But now I have 1 more question:

My goal is to create a Powershell script that executes my SQL scripts. How can I run my sql scripts in Powershell that are stored in c:\scripts for example?

This is my current source code:

...

$DBConnectionString = "Driver={PostgreSQL ODBC Driver(UNICODE)};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 = "CREATE TABLE accounts (
    user_id serial PRIMARY KEY,
    username VARCHAR ( 50 ) UNIQUE NOT NULL,
    password VARCHAR ( 50 ) NOT NULL,
    email VARCHAR ( 255 ) UNIQUE NOT NULL,
    created_on TIMESTAMP NOT NULL,
        last_login TIMESTAMP 
);";
$DBCmd.ExecuteReader();
$DBConn.Close();

UPDATE 1:

...

$DBConnectionString = "Driver={PostgreSQL ODBC Driver(UNICODE)};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();

/* 
Here I want to go to a folder where all my SQL files are and I want to run an SQL file
*/

);";
$DBCmd.ExecuteReader();
$DBConn.Close();
4
  • Unfortunately not. I want to execute SQL scripts via Powershell. I.e. establish connection --> execute sql scripts --> close connection again. Commented Jan 10, 2022 at 15:46
  • 1
    The code works but I want to replace the command block and run a sql file instead. I updated my Code. Maybe that will make it more understandable Commented Jan 10, 2022 at 15:51
  • I misread your question; it's definitely clear what you're looking for now. Commented Jan 10, 2022 at 16:18
  • I've updated the answer to show a solution that merges the content of all SQL script files to submit the merged content as a single command (assuming that is supported). Commented Jan 10, 2022 at 16:23

1 Answer 1

1

Perhaps you're looking for something like:

# ...
Get-ChildItem C:\Scripts -Filter *.psql | ForEach-Object {
  # Execute the content of each file as its own command.
  $DBCmd.CommandText = $_ | Get-Content -Raw
  $DBCmd.ExecuteReader();
}
# ...

If you want to merge the contents of all *.psql files and submit it as a single command:

# ...
# Execute the merged content of all script files as a single command.
$DBCmd.CommandText = (Get-Content -Raw C:\Scripts\*.psql) -join "`n"
$DBCmd.ExecuteReader();
# ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.