最近,我想在PowerShell中的$profile
中创建一个函数,该函数连接到Postgres服务器并执行查询。
该函数看起来像这样:
function db{
Param(
[string]$provider = "PostgreSQL",
[string]$type = "UNICODE",
[string]$server = "localhost",
[string]$port = "5432",
[string]$db = "dbname",
[string]$uid = "username",
[string]$pwd = "password",
[string]$q = ""
)
#future upgrade: read default parameters from file
$DBConnectionString = 'Driver={'+$driver+' '+$type+'}:Server='+$server+';Port='+$port+';Database='+$db+';Uid='+$uid+';Pwd='+$pwd+';';
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
Write-Output "this connectionstring: $DBConnectionString";
$DBConn.Open();
$DBCmd = $DBConn.CreateCommand();
$DBCmd.CommandText = $q;
$DBCmd.ExecuteReader();
$DBConn.Close();
}
如您所见,我放置了一个Write-Output
,以便可以看到连接字符串的值。
输出中给我的错误是:
Exception setting "ConnectionString": "Format of the initialization string does not conform to specification starting at index 0." At C:\Users\...\Microsoft.PowerShell_profile.ps1:84 char:1 + $DBConn.ConnectionString = $DBConnectionString
Write-Output
返回:
this connectionstring: Driver={PostgreSQL UNICODE}:Server=localhost;Port=5432;Database=dbname;Uid=username;Pwd=password;
因此$DBConnectionString
变量中包含的值是正确的。