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

<#
.DESCRIPTION
    This script is meant to be called primarily through the Test-CachedCredential Function
    It creates secured credentials as JSON-based (.ESS) text files that contains the password as an encrypted standard string.
    Cryptographic access is limited to the user account that created the file so they are stored in a user specific Filepath
    The Metadata for preset credentials is maintained in $Global:PS_CredentialMetadata (via Import/Export-CredentialMetadata)
 
#>

function New-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("Credential", (New-StaticParameter -ParamName "Credential" -ValueType pscredential -Mandatory:$false))
        $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
    {
        # Create Credential Object
        $Principal = if($CM.domain){("$($CM.userName)@$($CM.domain)").ToLower()}else{$CM.userName}
        if(!$Credential){$Credential = Get-Credential -UserName $Principal -Message $CM.hint}
        
        # Establish filepath
        $FilePath = "$CredentialPath\$($CM.name).ess"
        #$Credential | Export-Clixml -Path $FilePath -Force
        
        # Create CredentialContainer Object
        $ESSObj = New-ESSObj -TargetName $CM.name -Comment $CM.hint -Credential $Credential | ConvertTo-Json 
        $ESSObj | out-file $FilePath -Encoding utf8 -Force
        
        $Test = Test-Path -Path $FilePath
        if($Test)
        {
            Write-Host "Created Credential in $ENV:Username's ESS File Cache" -ForegroundColor Yellow
            Write-Host "Name: `"$($CM.Name)`" Username: `"$Principal`"" -ForegroundColor Yellow
        }
        else
        {
            write-host "Failed to Create .ess file in $ENV:Username's Cache"
        }
    } 
}