[英]How can I execute SQL scripts via Powershell?
I managed to connect to a PostgreSQL database via PowerShell after ages of trying.经过多年的尝试,我设法通过 PowerShell 连接到 PostgreSQL 数据库。
But now I have 1 more question:但现在我还有 1 个问题:
My goal is to create a Powershell script that executes my SQL scripts.我的目标是创建一个 Powershell 脚本来执行我的 SQL 脚本。 How can I run my sql scripts in Powershell that are stored in c:\scripts for example?例如,如何在 Powershell 中运行我的 sql 脚本,这些脚本存储在 c:\scripts 中?
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:更新 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();
I'm not familiar with PostgreSQL and there may be better ways of doing this (and I can't test the code), but perhaps you're looking for something like:我不熟悉 PostgreSQL 可能有更好的方法(我无法测试代码),但也许你正在寻找类似的东西:
# ...
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 that as a single command (assuming that is supported):如果要合并所有*.psql
文件的内容并将其作为单个命令提交(假设受支持):
# ...
# Execute the merged content of all script files as a single command.
$DBCmd.CommandText = (Get-Content -Raw C:\Scripts\*.psql) -join "`n"
$DBCmd.ExecuteReader();
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.