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 un-encrypted 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 run-time  I know this is not the most secure solution, but it sure beats storing the password in plain text.

I’ve read that the -Credential flag is available in PowerShell 3.0 but I was forced to use v 2.0 on the server I was working on. Well not really forced, just didn’t want to jump through all the hoops to get approval for an upgrade.

#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 DOMAIN\USER Account the file was generated using this command
# 		read-host -assecurestring | convertfrom-securestring | out-file C:\scripts\SecureFile.txt
$username = "DOMAIN\USERNAME"
$sourcePath = "\\someserver\x$\somefile.ext"
$destpath = "x:\some path\"
$securefile = "C:\scripts\SecureFile.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 \\server\x$ $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 \\server\x$ /DELETE

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s