2013-08-26 32 views
0

我有一個連接到數據庫的PowerShell腳本:PowerShell如何來的ConnectionString加密數據庫

$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 
+0

你有什麼錯誤? – Mitul

回答

3

關於第一個錯誤

首先嚐試這種在PS主機

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

和SQL Server不期望與System.Management.Automation.PSCredential連接字符串,它需要它的用戶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 
+0

這個效果很好,謝謝! – Glowie