Reputation: 21
I have a dilema.
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:
$credential = Get-Credential
$credential.Password | ConvertFrom-SecureString | Set-Content e:\temp\password.txt
And then in the script converting it back to plain text (to be used in a connection string)
$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=<mydatabase>;Initial Catalog='<mytable>';User ID=tng ;Password=$Unsecurepassword;"
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?
I tried this technet article but it appears that it still requires local log on from the other account.
Upvotes: 1
Views: 2846
Reputation: 21
Found the answer - I needed to add a key to the secure string:
When creating the file - adding in the $key:
[byte[]] $key = (1..16)
$credential = Get-Credential
$credential.Password | ConvertFrom-SecureString -key $key | Set-Content e:\temp\password.txt
And then when reading it back in:
$passwordfile = "E:\temp\password.txt"
[byte[]] $key = (1..16)
$securePassword = Get-Content $passwordfile | ConvertTo-SecureString -Key $key
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securepassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Answer found thanks to this link
Upvotes: 1