DSCResources/VE_ROABuildingBlock/VE_ROABuildingBlock.psm1

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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
data localizedData {
    # Localized messages; culture="en-US"
    ConvertFrom-StringData @'
        CannotFindPathError = Cannot find path '{0}' because it does not exist.
 
        ResourceCorrectPropertyState = Resource property '{0}' is in the desired state.
        ResourceIncorrectPropertyState = Resource property '{0}' is NOT in the desired state. Expected '{1}', actual '{2}'.
        ResourceInDesiredState = Resource '{0}' is in the desired state.
        ResourceNotInDesiredState = Resource '{0}' is NOT in the desired state.
        ImportingBuildingBlock = Importing building block '{0}'.
        DeletingBuildingBlock = Deleting building block '{0}'.
'@

}

#region Private

function SetBuildingBlockFileHash {
<#
    .SYNOPSIS
        Updates the registry with friendly names and hash values.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [System.String] $RegistryName,

        [Parameter(Mandatory)]
        [System.String] $FileHash
    )
    process {

        if (-not (Test-Path -Path $script:DefaultRegistryPath -PathType Container)) {
            $registryParentPath = Split-Path -Path $script:DefaultRegistryPath -Parent;
            $registryKeyName = Split-Path -Path $script:DefaultRegistryPath -Leaf;
            [ref] $null = New-Item -Path $registryParentPath -ItemType Directory -Name $registryKeyName;
        }

        [ref] $null = Set-ItemProperty -Path $script:DefaultRegistryPath -Name $RegistryName -Value $FileHash;

    } #end process
} #end function SetBuildingBlockFileHash


function ResolveBuildingBlock {
<#
    .SYNOPSIS
        Returns a list of resolved RES ONE Automation building block files/hashes.
#>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCustomObject])]
    param (
        ## File path containing RES ONE Automation Manager building blocks.
        [Parameter(Mandatory)]
        [System.String] $Path
    )
    process {

        $paths = @()
        foreach ($filePath in $Path) {

            if (-not (Test-Path -Path $filePath)) {

                $exMessage = $localizedData.CannotFindPathError -f $filePath;
                $ex = New-Object System.Management.Automation.ItemNotFoundException $exMessage;
                $category = [System.Management.Automation.ErrorCategory]::ObjectNotFound;
                $errRecord = New-Object System.Management.Automation.ErrorRecord $ex, 'PathNotFound', $category, $filePath;
                $psCmdlet.WriteError($errRecord);
                continue;
            }

            # Resolve any wildcards that might be in the path
            $provider = $null;
            $paths += $psCmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath($filePath, [ref] $provider);

        }

        foreach ($filePath in $paths) {
            Write-Output -InputObject ([PSCustomObject] @{
                Path = $filePath;
                FileHash = (Get-FileHash -Path $filePath -Algorithm MD5).Hash;
                RegistryName = (Split-Path -Path $filePath -Leaf).Replace(' ','').Replace('-','').Replace('.','_');
            });
        }

    } #end process
} #end function ResolveBuildingBlock

#endregion Private

function Get-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param (
        ## RES ONE Automation database server name/instance (equivalient to DBSERVER).
        [Parameter(Mandatory)]
        [System.String] $Path,

        ## RES ONE Automation authentication credential.
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()] $Credential,

        ## Credential supplied is an internal RES ONE Automation user.
        [Parameter()]
        [System.Boolean] $IsRESONEAutomationCredential,

        ## Delete the building block from disk after import.
        [Parameter()]
        [System.Boolean] $DeleteFromDisk
    )
    process {

        $buildingBlocks = ResolveBuildingBlock -Path $Path;
        foreach ($bb in $buildingBlocks) {
            Write-Output -InputObject @{ Path = $bb.Path; }
        }

    }
} #end function Get-TargetResource


function Test-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param (
        [Parameter(Mandatory)]
        [System.String] $Path,

        ## RES ONE Automation authentication credential.
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()] $Credential,

        [Parameter()]
        [System.Boolean] $IsRESONEAutomationCredential,

        ## Delete the building block from disk after import.
        [Parameter()]
        [System.Boolean] $DeleteFromDisk
    )
    process {

        $inCompliance = $true;
        $buildingBlocks = ResolveBuildingBlock -Path $Path;

        foreach ($bb in $buildingBlocks) {

            $registryName = $bb.RegistryName;
            $registryHash = (Get-ItemProperty -Path $script:DefaultRegistryPath -Name $bb.RegistryName -ErrorAction SilentlyContinue).$RegistryName;
            if ($bb.FileHash -ne $registryHash) {

                Write-Verbose -Message ($localizedData.ResourceIncorrectPropertyState -f $bb.RegistryName, $bb.FileHash, $registryHash);
                $inCompliance = $false;
            }
            else {

                Write-Verbose -Message ($localizedData.ResourceCorrectPropertyState -f $bb.RegistryName);
            }

        }

        if ($inCompliance) {

            Write-Verbose -Message ($localizedData.ResourceInDesiredState -f $Path);
            return $true;
        }
        else {

            Write-Verbose -Message ($localizedData.ResourceNotInDesiredState -f $Path);
            return $false;
        }

    }
} #end function Test-TargetResource


function Set-TargetResource {
    [CmdletBinding()]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
    param (
        [Parameter(Mandatory)]
        [System.String] $Path,

        ## RES ONE Automation authentication credential.
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()] $Credential,

        [Parameter()]
        [System.Boolean] $IsRESONEAutomationCredential,

        ## Delete the building block from disk after import.
        [Parameter()]
        [System.Boolean] $DeleteFromDisk
    )
    process {

        $buildingBlocks = ResolveBuildingBlock -Path $Path;

        foreach ($bb in $buildingBlocks) {

            $registryName = $bb.RegistryName;
            $registryHash = (Get-ItemProperty -Path $script:DefaultRegistryPath -Name $bb.RegistryName -ErrorAction SilentlyContinue).$registryName;
            if ($bb.FileHash -ne $registryHash) {

                try {

                    ## Import the building block
                    $PSBoundParameters['Path'] = $bb.Path;
                    [ref] $null = $PSBoundParameters.Remove('DeleteFromDisk');
                    Write-Verbose -Message ($localizedData.ImportingBuildingBlock -f $bb.Path);
                    Import-ROABuildingBlockFile @PSBoundParameters;

                    ## Update the registry/hash value
                    SetBuildingBlockFileHash -RegistryName $bb.RegistryName -FileHash $bb.FileHash;

                    if ($DeleteFromDisk) {
                        
                        ## TODO: Needs to delete any associated .xbb file too
                        Write-Verbose -Message ($localizedData.DeletingBuildingBlock -f $bb.Path);
                        Remove-Item -Path $bb.Path -Force;
                    }
                }
                catch {

                    throw;
                }
            }

        } #end foreach building block

    } #end process
} #end function Set-TargetResource


## Import the ROACommon library functions
$moduleRoot = Split-Path -Path $MyInvocation.MyCommand.Path -Parent;
$moduleParent = Split-Path -Path $moduleRoot -Parent;
Import-Module (Join-Path -Path $moduleParent -ChildPath 'ROACommon') -Force;

$script:DefaultRegistryPath = 'HKLM:\SOFTWARE\Virtual Engine\RESONEAutomationDsc';

Export-ModuleMember -Function *-TargetResource;