Functions/Authentication/PSCredential/MCM/New-MCMCredential.ps1

<#
.DESCRIPTION
    This script is meant to be called primarily through the Test-MCMCredential Script
    It creates secured credentials in the Microsoft Credential Manager
    The target, username, and hint bindings are maintained in the MCI Memspace (via Import-MCMCredentialInfo)
 
#>

function New-MCMCredential
    {
    [CmdletBinding()]
    Param()
    DynamicParam 
        {
        # Get MCM Credential Info
        $MCMInfo = Import-MCMCredentialInfo

        # Dynamic Parameter for MCI Targets
        $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $ParameterName = "Target"
        $RunTimeParameter = New-DynamicParameter -ParamName $ParameterName -ValueType string -DataSet $MCMInfo.Target -Mandatory:$true
        $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
        return $RuntimeParameterDictionary   
        }
    
    Begin
        {
        # Burn in parameter variables from Runtime Parameter Dictionary
        foreach ($key in $RuntimeParameterDictionary.keys){New-Variable -Name $key -Value $RuntimeParameterDictionary.$key.value}
        
        # Get Specific Credential from Info Map
        $MCI = $MCMInfo | where target -eq $target
        }

    Process
        {
        if ($MCI)
            {
            $Credential = Get-Credential -UserName $MCI.User -Message $MCI.Hint
            $NEW = New-StoredCredential -Target $MCI.Target -Credentials $Credential -Comment $MCI.Hint -Persist Enterprise
            if($NEW)
                {
                Write-Host "Created new credential in $ENV:Username's Vault" -ForegroundColor Yellow
                Write-Host "Target: $($MCI.target) Username: $($Credential.username)" -ForegroundColor Yellow
                }
            }
        else
            {Throw "Could not retrieve MCI Data for this target ($target) using `"Import-MCMCredentialInfo`""}
        } 
    }