src/Connection/Get-XrmConnection.ps1

<#
    .SYNOPSIS
    Get connections from XrmToolBox.

    .DESCRIPTION
    Browse and retrieve information from XrmToolBox saved connections.
    With Name, the connection file is read and becomes the current connection ($Global:XrmContext.CurrentConnection); with InstanceName too, the instance becomes the current instance ($Global:XrmContext.CurrentInstance).

    .PARAMETER ListAvailable
    Specify if you want to see all connections or all instances.
    Without Name: list the saved connections. With Name: output the instances of the connection before the connection.

    .PARAMETER XtbConnectionPath
    XTB connections folder path. A relative path is read from the PowerShell location. (Default: MscrmTools\XrmToolBox\Connections in APPDATA)

    .PARAMETER Name
    XrmToolBox connection name (connection file name without .xml). Mandatory without ListAvailable.

    .PARAMETER InstanceName
    Name of the instance to select in the connection (its ConnectionName in the XrmToolBox file). Used with Name.

    .OUTPUTS
    PSCustomObject. With Name: the connection (Name, FilePath, Instances...), preceded by its instances with ListAvailable. With Name and InstanceName: the instance (Name, Url, UniqueName, ConnectionString...). With ListAvailable only: one object per saved connection, with its Name.

    .EXAMPLE
    Get-XrmConnection -ListAvailable;

    .EXAMPLE
    $instance = Get-XrmConnection -Name "Contoso" -InstanceName "Contoso - Dev";
    $instance.Url;

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Get-XrmConnection.md
#>

function Get-XrmConnection {
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory = $false)]
        [Switch]
        $ListAvailable,

        [Parameter(Mandatory = $false)]
        [String]
        $XtbConnectionPath = [System.IO.Path]::Combine((Get-XrmAppDataPathInternal), "MscrmTools", "XrmToolBox", "Connections")
    )
    dynamicparam {
        $dynamicParameters = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary;
             
        # Define Dynamic Parameter : Name
        $nameParameterAttributes = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute];
        $nameParameterAttribute = New-Object System.Management.Automation.ParameterAttribute;
        $nameParameterAttribute.Mandatory = (-not $ListAvailable);        
        $nameParameterAttributes.Add($nameParameterAttribute);        
        $nameParameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter("Name", [string], $nameParameterAttributes);
        $dynamicParameters.Add("Name", $nameParameter);
                                 
        # Define Dynamic Parameter : InstanceName
        $instanceNameParameterAttributes = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute];
        $instanceNameParameterAttribute = New-Object System.Management.Automation.ParameterAttribute;
        $instanceNameParameterAttributes.Add($instanceNameParameterAttribute);        
        $instanceNameParameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter("InstanceName", [string], $instanceNameParameterAttributes);
        $dynamicParameters.Add("InstanceName", $instanceNameParameter);
              
        return $dynamicParameters;    
    }
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        # Relative to the PowerShell location, not to the folder of the process (M25)
        if ($XtbConnectionPath) { $XtbConnectionPath = Resolve-XrmPathInternal -Path $XtbConnectionPath; }

        $name = $PSBoundParameters.Name;
        $instanceName = $PSBoundParameters.InstanceName;
               
        if ($PSBoundParameters.ContainsKey('Name')) {  
            $targetFilePath = [System.IO.Path]::Combine($XtbConnectionPath, "$($Name).xml");
            
            $connection = Import-XrmConnection -FilePath $targetFilePath;
            if (-not $Global:XrmContext) {
                $Global:XrmContext = New-XrmContext;
            }
            $Global:XrmContext.CurrentConnection = $connection;

            if ($PSBoundParameters.ContainsKey('InstanceName')) {
                $instance = $connection.Instances | Where-Object -Property "Name" -EQ -Value $InstanceName;
                $Global:XrmContext.CurrentInstance = $instance;
                $instance;                
            }
            else {
                if ($ListAvailable) {                    
                    $connection.Instances;
                }
                $connection;
            }
        }
        else {            
            $xtbConnectionFilePath = [System.IO.Path]::Combine($XtbConnectionPath, "MscrmTools.ConnectionsList.xml");
            $xtbContent = [xml] [IO.File]::ReadAllText($xtbConnectionFilePath);

            $connections = @();
            foreach ($file in $xtbContent.ConnectionsList.Files.ConnectionFile) {
                $connection = Import-XrmConnection -FilePath $file.Path;
                $connections += $connection;
            }
            $connections | Select-Object Name;
        }   
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Get-XrmConnection -Alias *;

Register-ArgumentCompleter -CommandName Get-XrmConnection -ParameterName "Name" -ScriptBlock {

    param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)

    $fileNames = @(Get-ChildItem -Path ([System.IO.Path]::Combine((Get-XrmAppDataPathInternal), "MscrmTools", "XrmToolBox", "Connections")) -Include "*.xml" -Recurse | Select-Object -Property BaseName);
    $validNames = @();
    $fileNames | Sort-Object -Property BaseName  | ForEach-Object {
        $validNames += $_.BaseName;
    }
    return $validNames | Where-Object { $_ -like "$wordToComplete*" };
}

Register-ArgumentCompleter -CommandName Get-XrmConnection -ParameterName "InstanceName" -ScriptBlock {

    param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)

    if (-not ($fakeBoundParameters.ContainsKey("Name"))) {
        return @();
    }
    $fileName = "$($fakeBoundParameters.Name).xml"; 
    $targetFilePath = [IO.Path]::Combine((Get-XrmAppDataPathInternal), "MscrmTools", "XrmToolBox", "Connections", $fileName);
    $connection = Import-XrmConnection -FilePath $targetFilePath;

    $validInstanceNames = @();
    $connection.Instances | Sort-Object -Property Name | ForEach-Object {
        $validInstanceNames += $_.Name;
    }           
    return $validInstanceNames | Where-Object { $_ -like "$wordToComplete*" };
}