Public/Invoke-LabSnippet.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function Invoke-LabSnippet
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [string[]]
        $Name,

        [hashtable]
        $LabParameter = @{}
    )

    begin
    {
        $scriptBlockOrder = @{}
        try { [AutomatedLab.LabTelemetry]::Instance.FunctionCalled($PSCmdlet.MyInvocation.InvocationName) } catch {}
    }

    process
    {
        foreach ($snip in $Name)
        {
            $snip = $snip -replace 'AutomatedLab\..*\.'
            $schnippet = Get-LabSnippet -Name $snip
            [string[]]$dependencies = ($schnippet.Tag | Where-Object { $_.StartsWith('DependsOn_') }) -replace 'DependsOn_'
            $scriptBlockOrder[($schnippet.Name -replace 'AutomatedLab\..*\.')] = $dependencies
        }
    }

    end
    {
        try
        {
            $order = Get-TopologicalSort -EdgeList $scriptBlockOrder -ErrorAction Stop
            Write-PSFMessage -Message "Calculated dependency graph: $($order -join ',')"
        }
        catch
        {
            Write-Error -ErrorRecord $_
            return
        }

        $snippets = Get-LabSnippet -Name $order
        if ($snippets.Count -ne $order.Count)
        {
            Write-PSFMessage -Level Error -Message "Missing dependencies in graph: $($order -join ',')"
        }

        foreach ($blockName in $order)
        {
            $schnippet = Get-LabSnippet -Name $blockName
            $block = $schnippet.ScriptBlock
            $clonedParam = $LabParameter.Clone()
            $commonParameters = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name
            $commandParameterKeys = $schnippet.Parameters
            $parameterKeys = $clonedParam.Keys.GetEnumerator() | ForEach-Object { $_ }
            
            [string[]]$keysToRemove = if ($parameterKeys -and $commandParameterKeys)
            {
                Compare-Object -ReferenceObject $commandParameterKeys -DifferenceObject $parameterKeys |
                Select-Object -ExpandProperty InputObject
            }
            else
            {
                @()
            }

            $keysToRemove = $keysToRemove + $commonParameters | Select-Object -Unique #remove the common parameters
            
            foreach ($key in $keysToRemove)
            {
                $clonedParam.Remove($key)
            }

            . $block @clonedParam
        }
    }
}