Question:
I’m trying to connect to a network share via powershell. The network share is on a different domain, so I need to supply credentials. Since New-PSDrive doesn’t support credentials, I was going to use net use, but I’m worried about putting my username/password right there in plaintext into the script. I forced ConvertTo-SecureString to make a secure string out of my password and then used ConvertFrom-SecureString and stored the result in a file. Then, I pulled it out of the file like this and tried net use:
1 2 3 |
$password = Get-Content net use q: "\\server\share" $password /user:domain\username |
But net use doesn’t recognize the secure string.
Anyone have any ideas on how to store the credentials so net use can use them? Thanks!
Answer:
Here’s two functions I use for encrypting/decrypting strings. They were adapted from a powershell.com post, but I don’t have the link handy. The idea is that your password file would store the output of Protect-String and then to convert back to a regular string, read in file and call UnProtect-String, that value returned from UnProtect string would be your $password variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
####################### function Protect-String { param([string]$InputString) $secure = ConvertTo-SecureString $InputString -asPlainText -force $export = $secure | ConvertFrom-SecureString write-output $export } #Protect-String ####################### function UnProtect-String { param([string]$InputString) $secure = ConvertTo-SecureString $InputString $helper = New-Object system.Management.Automation.PSCredential("SQLPSX", $secure) $plain = $helper.GetNetworkCredential().Password write-output $plain } #UnProtect-String |