Functions/Connection/Import-CdsConnection.ps1

<#
    .SYNOPSIS
    Export CDS Connection Object From File
#>


function Unprotect-CdsPassword([string] $pass) {
    $secureString = ConvertTo-SecureString -String ($pass);
    $pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString);
    $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto($pointer);
    return $password;
}

function Import-CdsConnection {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $FilePath,

        [Parameter(Mandatory = $false)]
        [switch]
        $DecryptPassword        
    )
    begin {   

        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        $fileContent = [xml] [IO.File]::ReadAllText($FilePath);
        $cdsConnection = New-CdsConnection;
        $cdsConnection.Name = $fileContent.Connection.Name;
        $cdsConnection.AuthType = $fileContent.Connection.AuthType;
        $cdsConnection.UserName = $fileContent.Connection.UserName;
        $clearPassword = "*******";
        if ($DecryptPassword) {
            $clearPassword = Unprotect-CdsPassword -pass $fileContent.Connection.UserPassword;
        }            
        $cdsConnection.UserPassword = $clearPassword;      
        $cdsConnection.ConnectionStringParameters = $fileContent.Connection.ConnectionStringParameters;        
            
        $cdsConnection.Region = $fileContent.Connection.Region;
        $cdsConnection.Instances = @();
        $fileContent.Connection.Instances.Instance | ForEach-Object {
            $instance = New-CdsInstance;
            $instance.Id = $_.Id;
            $instance.Name = $_.Name;
            $instance.UniqueName = $_.UniqueName;
            $instance.DisplayName = $_.DisplayName;
            $instance.Url = $_.Url;
            $instance.AdminApiUrl = $_.AdminApiUrl;
            $instance.ApiUrl = $_.ApiUrl;
            $instance.TenantId = $_.TenantId;
            $instance.EnviromentId = $_.EnviromentId;
            $instance.ConnectionString = $_.ConnectionString.Replace($fileContent.Connection.UserPassword, $clearPassword);           

            $cdsConnection.Instances += $instance;
        }

        $cdsConnection;
    }
    end {       
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Import-CdsConnection -Alias *;