Functions/Import-ARMtemplate.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#Requires -Version 5.0
function Import-ARMtemplate
{
<#
.SYNOPSIS
    Import an ARM template.
 
.DESCRIPTION
    This Cmdlet imports an ARM template from a file or from a JSON-string.
 
.PARAMETER JsonString
    A JSON string that is an ARM template
 
.PARAMETER FileName
    A file that contains a JSON ARM template
 
.EXAMPLE
    Get-ChildItem -Path .\TestFiles\SimpleVM.json | Import-ARMtemplate
    Get-ARMtemplate
 
.EXAMPLE
    # Copy an ARM template to the clipboard
 
    Get-ClipBoard | Import-ARMtemplate
    Get-ARMtemplate
 
.EXAMPLE
    Import-ARMtemplate -FileName .\TestFiles\SimpleVM.json
    Get-ARMtemplate
 
.INPUTS
    string
 
.OUTPUTS
     
 
.NOTES
    Author: Tore Groneng
    Website: www.firstpoint.no
    Twitter: @ToreGroneng
#>

[cmdletbinding()]
Param(
    [Parameter(ValueFromPipeline, ParameterSetName="AsString")]
    [string]
    $JsonString
    ,
    [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName="FromFile")]
    [System.IO.FileInfo]
    [Alias("FullName")]
    $FileName
    ,
    [switch]$PassThru
)

Begin
{
    $f = $MyInvocation.InvocationName
    Write-Verbose -Message "$f - START"
    $sb = New-Object System.Text.StringBuilder
}

Process
{
    if ($PSBoundParameters.ContainsKey("FileName"))
    {        
        $fileNameType = $FileName.GetType().Name
        if ($fileNameType -eq 'FileInfo')
        {
            $FileName = $FileName.FullName
        }        
        $JsonString = Get-Content -Path $FileName -Encoding UTF8            
    }

    if ($JsonString)
    {
        $null = $sb.Append($JsonString + [environment]::NewLine)
    }
}

End
{    
    if ($sb.Length -gt 0)
    {
        $jsonString = $sb.ToString()        
        Write-Verbose -Message "$f - $jsonString"
        
        $templateObject = $jsonString | ConvertFrom-Json

        if ($PassThru.IsPresent)
        {
            $templateObject
        }
        else
        {
            $script:Template = $templateObject
        }
    }
}

}