Storing PowerShell Credentials in the local user registry


From time to time, it may be necessary to save credentials for automating some portion of a script or function. Here is a method to save and retrieve those credentials as a secure string from the current user's registry hive as opposed to saving them in plain text or as a secure string in a file.  Copy/paste the following into a .ps1 (or download the attached script) and run as the user account under which you want to store registry credentials.

The final output of the script will the the code snippet necessary to insert into your script that you can use to call the specific credential you stored.  Be sure to store and retrieve the credentials under the user context your script will be running!

I've screencapped what it looks like when you run it (minus the Get-Credential prompt, since I wanted you to be able to see everything that happens afterwards).  Copy/paste the script or download the full one at the bottom of the post.

  1.  Download and run the script.  When you first run it, you're promted for an application or organization name.  This is going to be the name of the registry key that gets created under HKCU\Software.  In this example, I named it MyApplicationName.  Since it's a new key, it tells you and creates it, and then you are immediately prompted for the credentials that you want to store.
  2. After you enter the credentials, the strings are extracted and stored, and information is displayed on how to call them.
  3. If you highlight and copy/paste the light blue text into PowerShell (when logged in to the computer as this user), you'll retrieve the stored credential object, as you can see below.

 

<#
Write-Credentials into HKCU Hive
comments / questions to aaron.guilmette@microsoft.com
#>

$OrgName = Read-Host "Enter Organization or Application Name"
Write-Host -ForegroundColor Green Storing $OrgName as $OrgName.Replace(" ","")
$OrgName = $OrgName.Replace(" ","")
If (!(Test-Path "HKCU:\Software\$OrgName\Credentials"))
    { 
    Try
        {
        Write-Host -ForegroundColor Red "Credentials Path Not Found."
        New-Item -Path "HKCU:\Software\$OrgName" -Name "Credentials" -Force
        }
    Catch
        {
        [System.Exception]
        Write-Host -Foreground Red "Unable to create path."
        }
    Finally
        {
        }
    }

$secureCredential = Get-Credential -Message "Enter service account credential in DOMAIN\Username or Username@Domain.com format."
$credentialName = Read-Host "Enter a name for this credential"
$securePasswordString = $secureCredential.Password | ConvertFrom-SecureString
$userNameString = $secureCredential.Username

Write-Host -ForegroundColor Green "Storing credential '$usernameString' under HKCU:\Software\$OrgName\Credentials\$credentialName."

New-Item -Path HKCU:\Software\$OrgName\Credentials\$credentialName
New-ItemProperty -Path HKCU:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name UserName -Value $userNameString
New-ItemProperty -Path HKCU:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name Password -Value $securePasswordString

Write-Host "To retrieve this credential, you must be logged in as the current user and copy/paste this"
Write-Host "into the credential area of your PowerShell script, referencing your credential as" '$credential'":"
Write-Host `n
Write-Host -ForegroundColor Cyan "     " '$secureCredUserName' "= (Get-ItemProperty -Path HKCU:\Software\$OrgName\Credentials\$credentialName).UserName"
Write-Host -ForegroundColor Cyan "     " '$secureCredPassword' "= (Get-ItemProperty -Path HKCU:\Software\$OrgName\Credentials\$credentialName).Password"
Write-Host -ForegroundColor Cyan `n
Write-Host -ForegroundColor Cyan "     " '$securePassword' "= ConvertTo-SecureString" '$secureCredPassword'
Write-Host -ForegroundColor Cyan "     " '$credential' "= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList" '$secureCredUserName, $securePassword'

To download the completed script, head over to the TN Gallery: https://gallery.technet.microsoft.com/Store-Credential-in-the-b0ea1328

Comments (4)

Cancel reply

  1. Sujithkumar says:

    Firstly, Thank you much for sharing the above script. it is certainly very useful in many cases.
    I ran the script and it was successful but whenever i am calling this stored credential it is throwing error. For an instance, while running “SyncMailPublicFolders.ps1” script using the stored credential it throws the below error;

    ————————————————————————————————

    Are you sure you want to perform this action?
    Performing operation “Remove file” on Target “C:\PFScripts\SYN-Mail-Enabled-Public-Folder\PublicFolder-Sync-Report”.
    [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is “Y”): A
    [11/20/2017 6:15:29 PM] Creating an Exchange Online remote session…
    InitializeExchangeOnlineRemoteSession : Unable to create a remote shell session to Exchange Online. The error is as
    follows: “Connecting to remote server outlook.office365.com failed with the following error message :
    [ClientAccessServer=VI1PR0601CA0026,BackEndServer=,RequestId=f9a0dd9d-b521-4dc0-8603-08bf261b7f5d,TimeStamp=11/20/2017
    5:15:28 PM] Access Denied For more information, see the about_Remote_Troubleshooting Help topic.”.
    At C:\PFScripts\SYN-Mail-Enabled-Public-Folder\PublicFolder-Sync-Script\PUBSYNCCRIPT.ps1:512 char:5
    + InitializeExchangeOnlineRemoteSession;
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,InitializeExchangeOnlineRemoteSession
    —————————————————————————————————————————————

    On the other hand, I am able to connect to exchange online PowerShell manually like mentioned below,
    —————————————————————————————————————–
    $LiveCred = Get-Credential
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection
    Import-PSSession $Session

    ————————————————————————————————————-

    but when i use store credential it throws error as mentioned below

    [PS] C:\PFScripts\SYN-Mail-Enabled-Public-Folder\PublicFolder-Sync-Script>$secureCredUserName = Get-ItemProperty -Path H
    KCU:\Software\MaerskTraining\Credentials\SUJITHADMACC4SYNCPUBLICFOLDER -Name UserName
    [PS] C:\PFScripts\SYN-Mail-Enabled-Public-Folder\PublicFolder-Sync-Script>$secureCredPassword = Get-ItemProperty -Path H
    KCU:\Software\MaerskTraining\Credentials\SUJITHADMACC4SYNCPUBLICFOLDER -Name Password
    [PS] C:\PFScripts\SYN-Mail-Enabled-Public-Folder\PublicFolder-Sync-Script>$securePassword = ConvertTo-SecureString $secu
    reCredPassword
    ConvertTo-SecureString : Input string was not in a correct format.
    At line:1 char:19
    + $securePassword = ConvertTo-SecureString $secureCredPassword
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [ConvertTo-SecureString], FormatException
    + FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

    ———————————————————————————————————————————

    Please assist!

    1. It looks like the code in the attached script was incorrect, though it was correct in the code you could copy/paste. I’ve updated the downloadable code and tested it, as well as updated the screen shots.

      1. It worked great!!!!!!

        Thank you very much for updating the information

Skip to main content