Storing Credentials to be used in Powershell Script

Ran into a need to store credentials for an account to run a powershell script. Examples of how you can use this would be:
1. Have the Service Desk run a script that will do a task higher than they have authorization with their normal accounts.
2. Running a script from a scheduled task
3. Just being lazy and hate typing username and password over and over

This is an example of that.

# Variables
$passwdpath = "C:\Auth\Passwd.txt"
$myusername = "username@domain.com"

# Does the file exist?, If not ask for Password and encrypt it
if(![System.IO.File]::Exists($passwdpath)){
read-host -prompt "Enter password to be encrypted in Passwd.txt " -assecurestring | convertfrom-securestring | out-file $passwdpath
}

# Script Foo Magic here
$mypass = cat $passwdpath | convertto-securestring
$mycreds = new-object `
-typename System.Management.Automation.PSCredential `
-argumentlist $myusername,$mypass

So what this is doing is checking for the Passwd.txt file and if it is not there asks for the password. It then encrypts that password within Passwd.txt.

You can also store the username in $myusername

Then anytime you need to pass the credentials for a task just pass $mycreds. That will be the credentials to run the task.

Update – Ok .. yeah I can hear all the Security Guys (Gals) out there yelling at the screen about storing credentials in files. Yes .. this is not the best solution on paper, but I am not saying to store you admin credentials here. Use common sense and restrict the account to the least privileges it needs and use logging to log who is running the script, and protect the file location .. blah blah blah .. Sometimes you have to do some things that are not best practice but Best for your environment.

Bookmark the permalink.

Comments are closed.