Public/New-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
function New-LabSnippet
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Description,

        [Parameter(Mandatory)]
        [ValidateSet('Sample', 'Snippet', 'CustomRole')]
        [string]
        $Type,

        [string[]]
        $Tag,

        [Parameter(Mandatory)]
        [scriptblock]
        $ScriptBlock,

        [string[]]
        $DependsOn,

        [switch]
        $Force,

        [switch]
        $NoExport
    )

    $existingSnippet = Get-LabSnippet -Name $Name
    try { [AutomatedLab.LabTelemetry]::Instance.FunctionCalled($PSCmdlet.MyInvocation.InvocationName) } catch {}

    if ($existingSnippet -and -not $Force)
    {
        Write-PSFMessage -Level Error -Message "$Type $Name already exists. Use -Force to overwrite."
        return
    }

    foreach ($dependency in $DependsOn)
    {
        if ($Tag -notcontains "DependsOn_$($dependency)")
        {
            $Tag += "DependsOn_$($dependency)"
        }

        if (Get-LabSnippet -Name $dependency) { continue }
        Write-PSFMessage -Level Warning -Message "Snippet dependency $dependency has not been registered."
    }

    $scriptblockName = 'AutomatedLab.{0}.{1}' -f $Type, $Name
    Set-PSFScriptblock -ScriptBlock $ScriptBlock -Name $scriptblockName -Tag $Tag -Description $Description -Global

    if ($NoExport) { return }

    Export-LabSnippet -Name $Name -DependsOn $DependsOn
}