Functions/Authentication/PSCredential/ESS/Get-ESSCredential.ps1

<#
.DESCRIPTION
    This script is meant to be called primarily through the Get-CachedCredential Function
    It retrieves secured credentials from XML-based (.ESS) text files that contain their password as an encrypted standard string.
    The Metadata for these credentials is maintained via Import/Export-CredentialMetadata
 
#>

function Get-ESSCredential
{    
    [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("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
    {
        # Establish filepath
        $FilePath = "$CredentialPath\$($CM.name).ess"
        
        # Retrieve Credential from ESS
        $Test = Test-Path -Path $FilePath
        $ESSCRED = if ($TEST)
        {
            try 
            {
            $RESP = Get-Content -Path $Filepath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
            $CredContainer = New-CredentialContainer -Name $RESP.TargetName -Description $RESP.Comment -Date $RESP.LastWritten -Username $RESP.userName -Credential (New-Credential -Username $RESP.userName -SecurePassword ($RESP.Password | ConvertTo-SecureString))
            if($CredContainer){$CredContainer.credential}
            } catch {$null}}
        if($ESSCRED){$ESSCRED}
    }
}