DSCResources/Grani_RegistryKey/Grani_RegistryKey.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#region Initialize

function Initialize {
    # Enum for Ensure
    Add-Type -TypeDefinition @"
        public enum EnsureType
        {
            Present,
            Absent
        }
"@
 -ErrorAction SilentlyContinue

    # Enum for RegistryRoot
    Add-Type -TypeDefinition @"
        public enum RegistryRoot
        {
            HKEY_CLASSES_ROOT,
            HKEY_CURRENT_CONFIG,
            HKEY_CURRENT_USER,
            HKEY_DYN_DATA,
            HKEY_LOCAL_MACHINE,
            HKEY_PERFORMANCE_DATA,
            HKEY_USERS
        }
"@
 -ErrorAction SilentlyContinue

    # Enum for RegistryShortName for PSDrive
    Add-Type -TypeDefinition @"
        public enum RegistryRootPSName
        {
            HKCU,
            HKLM
        }
"@
 -ErrorAction SilentlyContinue

    $PSRegistryNameToFullName = [PSCustomObject]@{
        [RegistryRootPSName]::HKCU.ToString() = [RegistryRoot]::HKEY_CURRENT_USER
        [RegistryRootPSName]::HKLM.ToString() = [RegistryRoot]::HKEY_LOCAL_MACHINE
    }

    $RegistryNameToRegistryObject = [PSCustomObject]@{
        [RegistryRoot]::HKEY_CLASSES_ROOT.ToString() = [Microsoft.Win32.Registry]::ClassesRoot
        [RegistryRoot]::HKEY_CURRENT_CONFIG.ToString() = [Microsoft.Win32.Registry]::CurrentConfig
        [RegistryRoot]::HKEY_CURRENT_USER.ToString() = [Microsoft.Win32.Registry]::CurrentUser
        [RegistryRoot]::HKEY_DYN_DATA.ToString() = [Microsoft.Win32.Registry]::DynData
        [RegistryRoot]::HKEY_LOCAL_MACHINE.ToString() = [Microsoft.Win32.Registry]::LocalMachine
        [RegistryRoot]::HKEY_PERFORMANCE_DATA.ToString() = [Microsoft.Win32.Registry]::PerformanceData
        [RegistryRoot]::HKEY_USERS.ToString() = [Microsoft.Win32.Registry]::Users
    }
}

. Initialize

#endregion

#region Message Definition

$verboseMessages = Data {
    ConvertFrom-StringData -StringData @"
"@

}

$debugMessages = Data {
    ConvertFrom-StringData -StringData @"
"@

}

$errorMessages = Data {
    ConvertFrom-StringData -StringData @"
"@

}

#endregion

#region *-TargetResource

function Get-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Key,

        [parameter(Mandatory = $true)]
        [ValidateSet("Present", "Absent")]
        [System.String]$Ensure
    )

    # Change Key to Resitry Path Style
    $regPath = ConvertToRegistryFullQualifiedPath -Key $Key;

    # check Registry Key Exists
    if (IsRegistoryPathExists -Path $regPath) {
        # exists
        $ensureResult = [EnsureType]::Present.ToString();
    }
    else {
        # not exists
        $ensureResult = [EnsureType]::Absent.ToString();
    }

    return $returnValue = @{
        Key = $Key
        Ensure = $ensureResult
    };
}

function Set-TargetResource {
    [CmdletBinding()]
    [OutputType([void])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Key,

        [parameter(Mandatory = $true)]
        [ValidateSet("Present", "Absent")]
        [System.String]$Ensure
    )

    # Change Key to Resitry Path Style
    $regPath = ConvertToRegistryFullQualifiedPath -Key $Key;

    if ($Ensure -eq [EnsureType]::Present) {
        # Create Registry Key
        SetRegistryKey -Path $regPath;
        return;
    }

    # Remove Registry Key
    RemoveRegistryKey -Path $regPath;
}

function Test-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Key,

        [parameter(Mandatory = $true)]
        [ValidateSet("Present", "Absent")]
        [System.String]$Ensure
    )
    return (Get-TargetResource -Key $Key -Ensure $Ensure).Ensure -eq $Ensure;
}

#endregion

#region Registry Path helper

function IsRegistoryPathExists {
    [CmdletBinding()]
    [OutputType([bool])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path
    )

    $root = GetRegistryRoot -Path $Path;
    $subkey = $Path -split "$root\\" | Select -Last 1;

    try {
        $result = $RegistryNameToRegistryObject.$root.OpenSubKey($subkey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadSubTree);
        if ($null -eq $result) {
            return $false;
        }
        return $true;
    }
    finally {
        if ($null -ne $result) { $result.Dispose(); }
    }
}

function SetRegistryKey {
    [CmdletBinding()]
    [OutputType([void])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path
    )

    $root = GetRegistryRoot -Path $Path;
    $subkey = $Path -split "$root\\" | Select -Last 1;

    try {
        # Create Key - even key contains hoge/piyo.
        $result = $RegistryNameToRegistryObject.$root.CreateSubKey($subkey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree);
    }
    finally {
        if ($null -ne $result) { $result.Dispose(); }
    }
}

function RemoveRegistryKey {
    [CmdletBinding()]
    [OutputType([void])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path
    )

    $root = GetRegistryRoot -Path $Path;
    $subkey = $Path -split "$root\\" | Select -Last 1;

    try {
        $result = $RegistryNameToRegistryObject.$root.DeleteSubKey($subkey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree)
    }
    finally {
        if ($null -ne $result) { $result.Dispose(); }
    }
}

function GetRegistryRoot {
    [CmdletBinding()]
    [OutputType([RegistryRoot])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path
    )

    $roots = [enum]::GetNames([RegistryRoot]);
    foreach ($root in $roots) {
        if ($Path.ToUpper().Contains($root)) {
            return [RegistryRoot]::$root;
        }
    }
    throw New-Object System.InvalidOperationException ("Could not retrieve RegistryRoot. Make sure you have passed full-qualified name like HKEY_LOCAL_MACHINE.");
}

#endregion

#region Registry Key helper

function ConvertToRegistryFullQualifiedPath {
    [CmdletBinding()]
    [OutputType([string])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Key
    )

    if (IsRegistryKeyRootFullQualified -Key $Key) {
        return "registry::{0}" -f $Key;
    }
    elseif (IsRegistryKeyRootPSDrive -Key $Key) {
        $fullQualifiedKey = ConvertPSDriveKeyToFullQualifiedKey -PSDriveKey $Key;
        return "registry::{0}" -f $fullQualifiedKey;
    }
    throw New-Object System.NullReferenceException ("Could not convert key '{0}' to FullQualified Key" -f $Key);
}

function ConvertPSDriveKeyToFullQualifiedKey {
    [CmdletBinding()]
    [OutputType([bool])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$PSDriveKey
    )

    $root = (GetRegistryPSDrive -PSDriveKey $PSDriveKey).ToSTring();
    $result = $PSDriveKey.Replace(":", "").Replace($root.ToString(), $PSRegistryNameToFullName.$root.ToString());
    if ($result -ne $null) {
        return $result;
    }
    throw New-Object System.NullReferenceException ("Could not convert key '{0}' to FullQualified Key" -f $PSDriveKey);
}

function GetRegistryPSDrive {
    [CmdletBinding()]
    [OutputType([RegistryRootPSName])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$PSDriveKey
    )

    $roots = [enum]::GetNames([RegistryRootPSName]);
    foreach ($root in $roots) {
        if ($PSDriveKey.ToUpper().Contains($root)) {
            return [RegistryRootPSName]::$root;
        }
    }
    throw New-Object System.InvalidOperationException ("Could not retrieve RegistryRoot. Make sure you have passed PS Drive like HKLM: .");
}

function IsRegistryKeyRootFullQualified {
    [CmdletBinding()]
    [OutputType([bool])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Key
    )

    $roots = [enum]::GetNames([RegistryRoot]);
    foreach ($root in $roots) {
        if ($Key.ToUpper().Contains($root)) {
            return $true;
        }
    }
    return $false;
}

function IsRegistryKeyRootPSDrive {
    [CmdletBinding()]
    [OutputType([bool])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Key
    )

    $roots = [enum]::GetNames([RegistryRootPSName]);
    foreach ($root in $roots) {
        if ($Key.ToUpper().Contains($root)) {
            return $true;
        }
    }
    return $false;
}

#endregion

Export-ModuleMember -Function *-TargetResource