Save Encrypted Passwords to Registry for PowerShell

Recently I needed to save passwords to share across scripts and wanted to:

  1. Avoid clear text passwords
  2. Avoid updating anything in each PS1 script file
  3. Securely store in a central place
  4. Make future password updates easy

After testing I found that ConvertTo-SecureString can be used with Set-ItemProperty to encrypt user text input and save to the Registry Current User hive (HKCU).   From here, multiple scripts on that machine can reuse the one central password.   However, it cannot be decrypted from any other machine.    That enables us to share one credential across many PS1 scripts while keeping any password updates centralized and easy to do.    Also, the reference pointer in each script is not a file path, UNC, or network share, but simply “HKCU:\Software” for a reliable lookup pipeline.

Hope you find this useful too.  Cheers!  shades_smile










param (
Function GetSecurePassword($user) {
	# Registry HKCU folder
	$path = "HKCU:\Software\AdminScript"
	if (!(Test-Path $path)) {md $path | Out-Null}
	$name = $user
	# Do we need to clear old paswords?
	if ($clearSavedPW) {
		Remove-ItemProperty -Path $path -Name $name -Confirm:$false -ErrorAction SilentlyContinue
		Write-Host "Deleted password OK for $name" -Fore Yellow
	# Do we have registry HKCU saved password?
	$hash = (Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue)."$name"
	# Prompt for input
	if (!$hash) {
		$sec = Read-Host "Enter Password for $name" -AsSecureString
		if (!$sec) {
			Write-Error "Exit - No password given"
		$hash = $sec | ConvertFrom-SecureString
		# Prompt to save to HKCU
		$save = Read-Host "Save to HKCU registry (secure hash) [Y/N]?"
		if ($save -like "Y*") {
			Set-ItemProperty -Path $path -Name $name -Value $hash -Force
			Write-Host "Saved password OK for $name" -Fore Yellow
	# Return
	return $hash
# Example usage for SharePoint Online (Office 365)
Import-Module Microsoft.Online.SharePoint.PowerShell -WarningAction SilentlyContinue
$admin = ""
$pass = GetSecurePassword $admin
$secpw = ConvertTo-SecureString -String $pass -AsPlainText -Force
$c = New-Object System.Management.Automation.PSCredential ($admin, $secpw)
Connect-SPOService -URL "" -Credential $c



Return to Top ▲Return to Top ▲