Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: How do I connect to a network folder on a different domain with stored non-plaintext username/password

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:

$password = Get-Content <locationOfStoredPasswordFile> | ConvertTo-SecureString
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!

like image 774
Jeshizaemon Avatar asked Jan 11 '11 19:01

Jeshizaemon


1 Answers

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.

#######################
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
like image 63
Chad Miller Avatar answered Nov 15 '22 05:11

Chad Miller