Functions/AzDevOps/Import-CdsSolutionsBuild.ps1

<#
    .SYNOPSIS
    Run build action to import solutions
#>

function Import-CdsSolutionsBuild {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $false)]
        [String]
        $ConnectionString = $env:CONNECTIONSTRING,

        [Parameter(Mandatory = $false)]
        [String]
        $ArtifactsPath = "$($Env:SYSTEM_DEFAULTWORKINGDIRECTORY)\Solutions\drop\",

        [Parameter(Mandatory = $false)]
        [String]
        $SolutionsImportOrder = $($env:SOLUTIONS_IMPORTORDER)
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
               
        $cdsClient = New-CdsClient -ConnectionString $ConnectionString;

        Write-HostAndLog -Message "ArtifactsPath = $ArtifactsPath" -Level INFO;
        Write-HostAndLog -Message "SolutionsImportOrder = $SolutionsImportOrder" -Level INFO;

        $solutionsToImport = $SolutionsImportOrder.Split(",");
        $solutionFilePaths = Get-ChildItem -Path "$ArtifactsPath\*.zip" -recurse;

        $orderedSolutions = @();
        foreach($solutionName in $solutionsToImport)
        {    
            $solutionFilePath = $solutionFilePaths | Where-Object { $_.Name.Contains($solutionName); };
            if(-not $solutionFilePath)
            {
                throw "Solution '$solutionName' not found in $($ArtifactsPath)";
            }
            $orderedSolutions += "$solutionName;$solutionFilePath";
        }

        Write-HostAndLog -Message "Solutions will be deployed in the following order:" -Level INFO;
        foreach($solution in $orderedSolutions)
        {
            $solutionName = $solution.ToString().Split(";")[0];
            Write-HostAndLog -Message " - $($solutionName)" -Level INFO;
        }

        foreach($solution in $orderedSolutions)
        {        
            $solutionUniqueName = $solution.ToString().Split(";")[0];
            $solutionFilePath = $solution.ToString().Split(";")[1];
            
            Write-HostAndLog -Message "Importing $solutionUniqueName from $solutionFilePath" -Level INFO;
            $cdsClient | Import-CdsSolution -SolutionUniqueName $solutionUniqueName -SolutionFilePath $solutionFilePath;
            Write-HostAndLog -Message "Solution $($_) successfully imported" -Level SUCCESS;
        }

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

Import-ModuleMember -Function Import-CdsSolutionsBuild -Alias *;