title: Powershell how to encrypt connectionstring to database
body: <p>I have a powershell script that connects to a database:</p>
  
  <pre><code>$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;"
  </code></pre>
  
  <p>But I don't want the plaintext password to be hardcoded into the script.</p>
  
  <p>So, I tried the following:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>And, I replaced the connection string with </p>
  
  <pre><code>$conn.ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;$credentials;"
  </code></pre>
  
  <p>But I am getting numerous errors.</p>
  
  <p>This script is run on a nightly basis, so it must get the password of the database automatically.</p>
  
  <p>EDIT:</p>
  
  <p>Below are the errors:</p>
  
  <pre><code>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. &lt;&lt;&lt;&lt; ConnectionString = "Server=10.10.10.1;Initial Catalog=my_database;$credentials;"
          + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
          + FullyQualifiedErrorId : PropertyAssignmentException
  </code></pre>
  
  <p>and</p>
  
  <pre><code>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. &lt;&lt;&lt;&lt; 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 
  </code></pre>
  
  <p>and finally</p>
  
  <pre><code>Exception calling "Open" with "0" argument(s): "The ConnectionString property has not been initialized." At C:\sandbox\script.ps1:98 char:11
      + $conn.Open &lt;&lt;&lt;&lt; ()
          + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
          + FullyQualifiedErrorId : DotNetMethodException
  </code></pre>