Store powershell credentials encrypted
Within powershell there is a object call PSCredential. This objects can be used to store and load credentials which can be used e.g. for connecting to a server, Storage, VMware, etc.
$credential = Get-Credential $credential | Export-CliXml -Path "C:\scripts\credential.xml"
If our script should run automatically we have to save this credentials to a file. With this little script it can be done. It creates an variable $credential and prompt us for the username and password. The password will be encrypted as a SecureString from Data Protection API (DPAPI). After this we exported this variable to an XML file to allow reading this easily into another script or command.
Importent is that the content of the file only can be decrypted by the current user. If I need this credentials for another account I have a little bit more work to do. In my case my Veeam Backup & Replication is running like all default installations in “Local System” context. If I want to store and use credentials within e.g. Pre-Job scripts, I have to store the credentials within this user context.
But the big question is how to do this?
I used PSExec for this because it can spawn a new process easily within another security context. I downloaded it and used this command to start a script with the two code lines above.
PsExec64.exe -i -s powershell.exe -ExecutionPolicy Unrestricted -Command "& 'C:\scripts\Save-Credential.ps1‘"
Now the credentials are encrypted with “Local System” and can be used with e.g. Backup and Replication for Pre- or Post-Job scripts.
2 Responses
[…] for accessing the source and destination clusters and then connect to this systems. In this article I will explain how I have saved the credentials and why I have done it in this […]
[…] Second thing you need to think of it the user account the script runs with. Since this will be triggered by Veeam Backup & Replication, the context most likely will be the System user. To be able to use encrypted credentials in a xml file, this should be created with PSEXEC to have the decryption right for the System user. Marco Hostmann has written a nice little article on how to do this: https://horstmann.in/store-powershell-credentials-encrypted/ […]