Helpers/Profile/Export-ProfileEnvironmentCredential.ps1


function Export-ProfileEnvironmentCredential
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateScript({ Test-Path -Path $_ })]
        [System.String]
        $Path,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Management.Automation.PSCredential[]]
        $Credential
    )

    process
    {
        foreach ($CredentialItem in $Credential)
        {
            # Convert the username (probably including a domain name) to a nice
            # string which can be used as variable and file name.
            if ($CredentialItem.Username -like '*\*')
            {
                $File = $CredentialItem.Username.Split('\', 2)[0] + '_' + $CredentialItem.Username.Split('\', 2)[1]
            }
            elseif ($CredentialItem.Username -like '*@*')
            {
                $File = $CredentialItem.Username.Split('@', 2)[1] + '_' + $CredentialItem.Username.Split('@', 2)[0]
            }
            else
            {
                $File = 'LOCALHOST_' + $CredentialItem.Username
            }

            # Remove all non alphabetic and non numeric characters expect the
            # underline and add the file extension.
            $File = $File.ToUpper() -replace '[^0-9a-zA-Z_]'
            $File = $File + '.credential.xml'

            $CredentialItem | Export-Clixml -Path (Join-Path -Path $Path -ChildPath $File) -Force
        }
    }
}