Powershell如何加密连接字符串到数据库

时间:2013-08-26 14:34:55

标签: database powershell database-connection

我有一个连接数据库的powershell脚本:

$conn = New-Object System.Data.SqlClient.SqlConnection

$conn.ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;User Id=my_username;Password=my_password;"

但我不希望将明文密码硬编码到脚本中。

所以,我尝试了以下内容:

read-host -assecurestring | convertfrom-securestring | out-file C:\PS\cred.txt
$password = get-content C:\PS\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "my_username",$password

然后,我用

替换了连接字符串
$conn.ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;$credentials;"

但是我遇到了很多错误。

此脚本每晚运行一次,因此必须自动获取数据库的密码。

编辑:

以下是错误:

Exception setting "ConnectionString": "Format of the initialization string does not conform to specification starting at index 46." At C:\sandbox\script.ps1:75 char:7
    + $conn. <<<< ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;$credentials;"
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : PropertyAssignmentException

Exception setting "ConnectionString": "Format of the initialization string does not conform to specification starting at index 46." At C:\sandbox\script.ps1:82 char:14
    + $conn_update. <<<< ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;$credentials;"
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : PropertyAssignmentException   Creating and executing the SQL Query at 8/26/2013 10:28:38 AM 

最后

Exception calling "Open" with "0" argument(s): "The ConnectionString property has not been initialized." At C:\sandbox\script.ps1:98 char:11
    + $conn.Open <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

1 个答案:

答案 0 :(得分:4)

关于第一个错误

首先在ps控制台中尝试此操作

PS C:\>"server=server10;Initail Catalog=database;$credentials"
server=server10;Initail Catalog=database;System.Management.automation.PSCredential

并且sql server不期望连接字符串与System.Management.Automation.PSCredential相关,并且它需要以user id =“myusername”的格式;密码= “密码”

所以这样做。首先从$ credentials对象中检索用户名和密码,并将它们存储在变量中,并将该变量放入connectionstring中。

$username = $credentials.UserName
$password = $credentials.GetNetworkCredentail().Password

PS C:\>"server=server10;Initial Catalog=database;user id=$username;password=$password"
server=server10;Initial Catalog=database;user id=my_username;password=sdfsjci34929