Tuesday, January 29, 2013

PowerShell Encrypted Password NET USE

I needed to copy a file from a UNC to a server today. In the past I have always used the NET USE command to connect to the share. The main problem with this is that I typically stored the password unencrypted in the script. Lame.


I figured there has to be a better way to do this. Turns out there is. Power Shell allows you to setup an encrypted password file, then decrypt that file on the fly at runtime. I know this is not the most secure solution, but it sure beats storing the password in plain text.


#Function used to decrypt password
function Decrypt([string]$exportfile)
{
$securepassword = ConvertTo-SecureString $exportfile
$helper = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$global:pass = $helper.GetNetworkCredential().Password
}



#Set some variables
# Secure file stores the password for the DOMAINUSER Account the file was generated using this command
# read-host -assecurestring | convertfrom-securestring | out-file C:scriptsSecureFile.txt
$username = "DOMAINUSERNAME"
$sourcePath = "\someserverx$somefile.ext"
$destpath = "x:some path"
$securefile = "C:scriptsSecureFile.txt"

#Open up the secure file and decrypt it
$exportfile = get-content $securefile
Decrypt $exportfile

#Map the Drive
#using old school NET USE command to map the drive. This will cache the credentials so the Copy-Item command will work.
net use \serverx$ $pass /USER:$username

#copy the File and delete the drive
# Clean up the NET USE command by deleting the connection.
Copy-Item $sourcePath -Destination $destPath
net use \serverx$ /DELETE

0 comments:

Post a Comment