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

Glo*_*wie 0 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;"
Run Code Online (Sandbox Code Playgroud)

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

所以,我尝试了以下方法:

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
Run Code Online (Sandbox Code Playgroud)

而且,我用

$conn.ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;$credentials;"
Run Code Online (Sandbox Code Playgroud)

但是我收到了很多错误。

这个脚本每晚运行一次,所以它必须自动获取数据库的密码。

编辑:

以下是错误:

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
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)

最后

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
Run Code Online (Sandbox Code Playgroud)

Mit*_*tul 5

关于第一个错误

首先在 ps 控制台中试试这个

PS C:\>"server=server10;Initail Catalog=database;$credentials"
server=server10;Initail Catalog=database;System.Management.automation.PSCredential
Run Code Online (Sandbox Code Playgroud)

并且 sql server 不需要 System.Management.Automation.PSCredential 的连接字符串,它需要它的格式为 user id="myusername"; 密码=“密码”

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

$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
Run Code Online (Sandbox Code Playgroud)