Functions/Authentication/PSCredential/Test-CachedCredential.ps1

<#
.DESCRIPTION
    It either creates or retrieves secured credentials in the selected Credentialing Cache (Microsoft Credential Manager or Encrypted SecureString Files)
    It is intended to be called by other modules for specific credentialing as part of their automatic processes.
    It also tests domain-identity based credentials for their expiry date, prompting for overwrite if they are stale.
    It leverages the Get-CachedCredential and New-CachedCredential functions to operate.
#>

function Test-CachedCredential
{
    [CmdletBinding()]
    Param()
    DynamicParam 
    {
        # Define Credential Metadata
        $Metadata = [array]($Global:PS_CredentialMetadata)

        # Dynamic Parameter Selecting Credential Name from Metadata
        $RuntimeParameterDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
        $RuntimeParameterDictionary.Add("Name", (New-DynamicParameter -ParamName "Name" -ValueType string -DataSet $Metadata.name -Mandatory:$true))
        $RuntimeParameterDictionary.Add("Cache", (New-DynamicParameter -ParamName "Cache" -ValueType string -DataSet @("MCM","ESS") -Mandatory:$false -DefaultValue $Global:PS_CredentialCacheType))
        $RuntimeParameterDictionary.Add("CredentialPath", (New-StaticParameter -ParamName "CredentialPath" -ValueType string -Mandatory:$false -DefaultValue $Global:PS_CredentialPath))
        return $RuntimeParameterDictionary
    }
    
    Begin
    {
        # Convert Runtime Parameter Dictionary into Available Constants
        foreach ($key in $RuntimeParameterDictionary.keys){New-Variable -Name $key -Value $RuntimeParameterDictionary.$key.value}
        $CM = $Metadata | where name -eq $Name
    }

    Process
    {
        $CachedCredential = switch ($Cache)
        {
            "MCM"
            {
                # Check for Existing Credential in MCM
                $MCMCredential = Get-MCMCredential -Name $Name
                if (!$MCMCredential)
                {
                    # Create new MCM Credential if one doesn't already exist
                    New-MCMCredential -Name $Name
                    $MCMCredential = Get-MCMCredential -name $Name
                }
                $MCMCredential
            }
            "ESS"
            {
                # Check for Existing Credential in ESS
                $ESSCredential = Get-ESSCredential -Name $Name
                if (!$ESSCredential)
                {
                    # Create new ESS Credential if one doesn't already exist
                    New-ESSCredential -Name $Name
                    $ESSCredential = Get-ESSCredential -name $Name
                }
                $ESSCredential
            }
        }


        # Check for creation and then output
        if($CachedCredential) {$CachedCredential}
        else {Throw "Could not retrieve/create new $Cache Credential for: $Name"}
        }
    }