title: Powershell and running scheduled task as other user
body: <p>I have a dilema. </p>
  
  <p>I am trying to set up a scheduled task in Windows that runs a powershell script as another user (a Service account that has access but no logon rights).  The issue is that we have been told by our security group to not code in passwords (obviously good advice) but the connection string for the SQL seems to need it in plain text.  I am getting around this by creating a password file:</p>
  
  <pre><code>$credential = Get-Credential
  $credential.Password | ConvertFrom-SecureString | Set-Content e:\temp\password.txt
  </code></pre>
  
  <p>And then in the script converting it back to plain text (to be used in a connection string)</p>
  
  <pre><code>$password = cat E:\temp\password.txt | ConvertTo-SecureString
  $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
  $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
  
  $connectionString = "Data Source=&lt;mydatabase&gt;;Initial Catalog='&lt;mytable&gt;';User ID=tng ;Password=$Unsecurepassword;"
  </code></pre>
  
  <p>The snag though, is that when I create the password file and run the script as myself it works great, but I can't seem to run this as a scheduled task.  In past experiences I have seen where the password file probably needs created by the service account running the scheduled task, but without local log on rights, I am not sure how to create this.  Any thoughts? </p>
  
  <p>I tried <a href="https://blogs.technet.microsoft.com/benshy/2012/06/04/using-a-powershell-script-to-run-as-a-different-user-elevate-the-process/" rel="nofollow">this technet article</a> but it appears that it still requires local log on from the other account.</p>