functions/public/Get-CredentialsFromStore.ps1

function Get-CredentialsFromStore {
    param (
        [Parameter(Mandatory = $true)]
        [string] $Target,
        [Parameter(Mandatory = $true)]
        [string] $UserName,
        [Parameter(Mandatory = $true)]
        [ValidateSet("LocalMachine", "Session", "Enterprise")]
        [string] $Persist,
        [Parameter(Mandatory = $true)]
        [ValidateSet("Generic")]
        [string] $Type,
        [string] $Message
    )
    process {
        $credentials = $null
        $counter = 0
        while (!$credentials -and $counter -lt 3) {
            $credentials = Get-StoredCredential -Target $Target -Type $Type
            if ($credentials.UserName -and $credentials.UserName -ne $UserName) {
                Write-DosMessage -Level "Information" -Message "Updating credentials $($Target) that were found in Windows Credential Manager."
                Remove-StoredCredential -Target $Target -Type $Type
                $credentials = $null
            }
            if (!$credentials) {
                $secureCredentials = Read-Host -Prompt $Message -AsSecureString
                $credentials = New-Object System.Management.Automation.PSCredential $UserName, $secureCredentials
                New-StoredCredential -Target $Target -Persist $Persist -Type $Type -Credentials $credentials | Out-Null
                Write-DosMessage -Level "Information" -Message "New credentials $($Target) added to Windows Credential Manager."
            }
            else {
                Write-DosMessage -Level "Information" -Message "Credentials $($Target) -> $($UserName) found in Windows Credential Manager."
            }
            $counter++
        }
    }
    end {
        if (!$credentials) {
            Write-DosMessage -Level "Fatal" -Message "Unable to retrieve credentials $($Target) from Windows Credential Manager."
        }
        Write-DosMessage -Level "Information" -Message "If the password for UserName: ""$UserName"" needs to be reset, delete the stored credential from Windows Credential Manager and rerun this installation."
        Write-DosMessage -Level "Information" -Message "Script to delete stored credential --> ""Remove-StoredCredential -Target '$Target' -Type '$Type'"""
        return $credentials
    }
}