How to store and read user credentials from Windows Credentials manager

I have got need to store my credentials in the Windows Credentials manager and get the stored username and password to use in a Powershell script which is used in unattended scheduled task. While exploring I noticed some people used the command Get-StoredCredential. After seeing this command name, I thought this is a built-in Powershell command and used it in my script, but I got the error “The term ‘Get-StoredCredential’ is not recognized as the name of a cmdlet” while running my script.

After exploring some more time found that this cmdlet is not a built-in command and comes under the Powershell module CredentialManager. So we need to install this module before using the commands New-StoredCredential and Get-StoredCredential.

Install-Module -Name CredentialManager

Run the below command to store credentials in the Windows Credentials manager.

New-StoredCredential -Target 'MyPSUserInfo' -UserName 'username' -Password 'mypwd'

The above command stores the credentials under the target name “MyPSUserInfo”. But, you can’t view the credentials in the Credential Manager UI (Control Panel\All Control Panel Items\Credential Manager). We have to set the Persist parameter as ‘LocalMachine‘ to view the stored credentials in the Credential Manager UI.

New-StoredCredential -Target 'MyPSUserInfo' -Persist 'LocalMachine' -UserName 'username' -Password 'mypwd' -Type Generic

You can read the stored user credential from the Windows Credentials manager using the below command.

$psCred = Get-StoredCredential -Target "MyPSUserInfo"
------ Use $psCred object with your command ------
Connect-MSolService -Credential $psCred

You will get the following error message if the CredentialManager PS module is not installed.

New-StoredCredential : The term ‘New-StoredCredential’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Advertisement

2 thoughts on “How to store and read user credentials from Windows Credentials manager”

  1. Run
    New-StoredCredential -Target “MyPSUserInfo” -UserName “username” -Password “mypwd”

    Then go to Control Panel\All Control Panel Items\Credential Manager
    Hit View Refresh

    But MyPSUserInfo does not appear.
    Should it?

    Reply
    • You need to set the Persist parameter as ‘LocalMachine‘ to view the stored credentials in the Control Panel Credential Manager UI. Use the below command and check the case again.

      New-StoredCredential -Target 'MyPSUserInfo' -Persist 'LocalMachine' -UserName 'username' -Password 'mypwd' -Type Generic

      Reply

Leave a Comment