Using Credentials In Production Scripts

I can’t count on both hands the number of times I have been tasked with creating a script that needs to be able to login to a remote system with credentials in a scheduled task. Over time, I have stored credentials on a file on the server which runs the scheduled tasks, and recently started investigating working with the windows credential store as well courtesy of the module CredentialManager but I am not fully convinced yet at this point. This mostly is due to the code being older - and I hate having to use DLL files unless I really have to.

In order to create stored credentials for use in scheduled tasks there are a few things to keep in mind. Storing credentials in a file is never 100% foolproof. If using the default settings of storing credentials to disk, the contents of the file will be encrypted based upon the computer and username. If the file is moved to another computer or is attempted to be accessed by another user the credentials will be inaccessible. However, if the account which is used to access the file is compromised then the credentials will also be compromised. That being said there are two functions which I use to store and retrieve credentials.

When looking at most other websites, the method they use to store credentials in a file only stores an encrypted version of the password. The username is not typically stored in the file in most examples, and instead of having to keep updating scripts in case credentials change I decided to create a function which includes the username with the password in the encrypted file. The function to convert a credential object to an encrypted file is below. Note that the functions are not fully production level - there are a few things to finalize but for the most part it gets the job done at the level it is at currently.

To use this function, you need to pass in the PSCredential object as well as the path to store the file. An example of running this is:

$credential = get-credential
New-LocalCredentialFile -credential $credential -path "c:\creds\schTask1.txt"

Running the above will store the credential object in the file located at c:\creds\schtask1.txt. If the file already exists, then it is overwritten. The function to then turn the file from a block of encrypted text back to a pscredential object is below.

To run the above code run:

$credential = ConvertFrom-CredentialFileToCredential -path "c:\creds\schTask1.txt"

This will then convert the contents back to a pscrential object. As a reminder, with the current script blocks, they only work with encrypting/decrypting the contents of the file under the same account and not through certificates. Eventually the code will be updated to include this, but that is a low priority at this time.