Store Secure Credentials in the Registry with PowerShell
This process will store secure credentials in the registry. It allows you to query those credentials and then pass them using PowerCLI to make a connection to vCenter.
This is a simple code snippet that will ask for credentials and then add them to the registry. To make this easier, you can have PowerShell create the key that will house the information and then add the proper values. I’m going to use HKEY_CURRENT_USER but feel free to store these in HKEY_LOCAL_MACHINE if necessary. To store information into HKLM, you may need to elevate your PowerShell environment to administrator. I find putting stuff in HKCU is much easier… and it has the added benefit of storing credentials with the user instead of the machine.
1 2 3 4 5 6 7 8 9 10 11 |
# Creates the structure $strRegistryKey = "HKCU:\SOFTWARE\MySoftware\Users" New-Item -Path $strRegistryKey -ItemType RegistryKey -Force # Gather credential information $secureCredential = Get-Credential -Message "Enter the username and password:" $securePassword = $secureCredential.Password | ConvertFrom-SecureString $strUsername = $secureCredential.Username # Add credentials to the registry New-ItemProperty -Path $strRegistryKey -PropertyType String -Name $strUsername -Value $securePassword |
This will add something like the following to your registry:
Notice that the Data column for administrator@vsphere.local will be the password you entered but in encrypted form.
Retrieve Secure Credentials from the Registry with PowerShell
Now that we have it stored, we need to pull the information and log into vCenter with PowerCLI.
1 2 3 |
# Retrieve password for current user $securePassword = (Get-ItemProperty -Path $strRegistryKey -Name $strUserName).$strUserName | ConvertTo-SecureString $secureCredentials = New-Object System.Management.Automation.PSCredential ($strUserName, $securePassword) |
I am not a fan on how the Get-ItemProperty works (where you have to call out the key name twice). Once within the command and then once again in dot notation. I understand they provide more information than just the value, it’s just…. weird in that you aren’t calling a normally named property, you are calling the key name as a property. I digress…. 🙂
Connect to vCenter with Secure Credentials – PowerCLI
Now that we have the credentials in a form we can pass on to vCenter, here is the code to make that connection with PowerCLI.
1 2 |
# Connect to vCenter Connect-VIServer vcenter01.vt.local -Credential $secureCredentials |
That’s it!