DSCResources/MSFT_xEnvironmentResource/MSFT_xEnvironmentResource.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
# This PS module contains functions for Desired State Configuration (DSC) "xEnvironment" resource

# Fallback message strings in en-US
DATA localizedData
{
    # culture = "en-US"
    ConvertFrom-StringData @'
        EnvVarCreated = (CREATE) Environment variable '{0}' with value '{1}'
        EnvVarSetError = (ERROR) Failed to set environment variable '{0}' to value '{1}'
        EnvVarPathSetError = (ERROR) Failed to add path '{0}' to environment variable '{1}' holding value '{2}'
        EnvVarRemoveError = (ERROR) Failed to remove environment variable '{0}' holding value '{1}'
        EnvVarPathRemoveError = (ERROR) Failed to remove path '{0}' from variable '{1}' holding value '{2}'
        EnvVarUnchanged = (UNCHANGED) Environment variable '{0}' with value '{1}'
        EnvVarUpdated = (UPDATE) Environment variable '{0}' from value '{1}' to value '{2}'
        EnvVarPathUnchanged = (UNCHANGED) Path environment variable '{0}' with value '{1}'
        EnvVarPathUpdated = (UPDATE) Environment variable '{0}' from value '{1}' to value '{2}'
        EnvVarNotFound = (NOT FOUND) Environment variable '{0}'
        EnvVarFound = (FOUND) Environment variable '{0}' with value '{1}'
        EnvVarFoundWithMisMatchingValue = (FOUND MISMATCH) Environment variable '{0}' with value '{1}' mismatched the specified value '{2}'
        EnvVarRemoved = (REMOVE) Environment variable '{0}'
'@

}
Import-LocalizedData  LocalizedData -filename MSFT_xEnvironmentResource.strings.psd1

 
#-------------------------------------
# Script-level Constants and Variables
#-------------------------------------
$EnvVarRegPathMachine = "HKLM:\\System\\CurrentControlSet\\Control\\Session Manager\\Environment"
$EnvVarRegPathUser = "HKCU:\\Environment"

$EnvironmentVariableTarget = @{ Process = 0; User = 1; Machine = 2 }
$MaxSystemEnvVariableLength = 1024
$MaxUserEnvVariableLength = 255

Function Throw-InvalidArgumentException
{
    param(
        [string] $Message,
        [string] $ParamName
    )
    
    $exception = new-object System.ArgumentException $Message,$ParamName
    $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception,$ParamName,"InvalidArgument",$null
    throw $errorRecord
}

function GetEnvironmentVariable
{
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $Name, 

        [parameter(Mandatory = $true)]
        [int] $Target
    )

    if ($Target -eq $EnvironmentVariableTarget.Process) 
    {
        return [System.Environment]::GetEnvironmentVariable($Name);
    }

    if ($Target -eq $EnvironmentVariableTarget.Machine)
    {
        $retVal = Get-ItemProperty $EnvVarRegPathMachine -Name $Name -ErrorAction SilentlyContinue
        return $retVal.$Name
    }

    if ($Target -eq $EnvironmentVariableTarget.User)
    {
        $retVal = Get-ItemProperty $EnvVarRegPathUser -Name $Name -ErrorAction SilentlyContinue
        return $retVal.$Name
    }
}

function SetEnvironmentVariable
{
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $Name, 

        [String] $Value,

        [parameter(Mandatory = $true)]
        [int] $Target
    )

    if ($Target -eq $EnvironmentVariableTarget.Process) 
    {
        [System.Environment]::SetEnvironmentVariable($Name, $Value);
    }

    if ($Target -eq $EnvironmentVariableTarget.Machine) 
    {
        if ($Name.Length -ge $MaxSystemEnvVariableLength) {
            Throw-InvalidArgumentException -Message "Argument is too long." -ParamName $Name
        }
        $Path = $EnvVarRegPathMachine
    }
    elseif ($Target -eq $EnvironmentVariableTarget.User) 
    {
        if ($Name.Length -ge $MaxUserEnvVariableLength) {
            Throw-InvalidArgumentException -Message "Argument is too long." -ParamName $Name
        }
        $Path = $EnvVarRegPathUser
    }

    $environmentKey = Get-ItemProperty $Path -Name $Name -ErrorAction SilentlyContinue
    if ($environmentKey) 
    {
        if (!$Value) 
        {
            Remove-ItemProperty $Path -Name $Name -ErrorAction SilentlyContinue
        }
        else 
        {
            Set-ItemProperty $Path -Name $Name -Value $Value -ErrorAction SilentlyContinue
        }
    }
}


#------------------------------
# The Get-TargetResource cmdlet
#------------------------------
FUNCTION Get-TargetResource
{    
    [OutputType([Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name       
    )
        
    $retVal = GetItemProperty $EnvVarRegPathMachine -Name $Name -Expand:$false -ErrorAction SilentlyContinue
    
    if($retVal -eq $null)
    {        
        Write-Verbose ($localizedData.EnvVarNotFound -f $Name)
        
        return @{Ensure='Absent'; Name=$Name}      
    }    

    Write-Verbose ($localizedData.EnvVarFound -f $Name, $retVal.$Name)

    return @{Ensure='Present'; Name=$Name; Value=$retVal.$Name}
}

function Set-EnvVar
{
    param
    (       
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,
        
        [ValidateNotNull()]
        [System.String]
        $Value = [String]::Empty
    )

    $err = Set-ItemProperty $EnvVarRegPathMachine -Name $Name -Value $Value 2>&1

    if($err)
    {
        Write-Verbose ($localizedData.EnvVarSetError -f $Name, $Value)

        throw $err
    }                

    try
    {
        if($value)
        {
            SetEnvironmentVariable -Name $Name -Value $Value -Target $EnvironmentVariableTarget.Machine
            SetEnvironmentVariable -Name $Name -Value $Value -Target $EnvironmentVariableTarget.Process
        }
    }
    catch 
    {
        Write-Verbose ($localizedData.EnvVarSetError -f $Name, $Value)

        throw $_
    }

}
function Remove-EnvVar
{
    param
    (       
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name
    )

    $curVarProperties = Get-ItemProperty $EnvVarRegPathMachine -Name $Name -ErrorAction SilentlyContinue
    $currentValueFromEnv = GetEnvironmentVariable -Name $name -Target $EnvironmentVariableTarget.Process

    if($curVarProperties -ne $null)
    {
        $err = Remove-ItemProperty $EnvVarRegPathMachine -Name $Name 2>&1

        if($err)
        {
            Write-Log -Message ($localizedData.EnvVarRemoveError -f $Name, $Value)

            throw $err
        }
    }

    if($currentValueFromEnv -ne $null)
    {
        try
        {
            SetEnvironmentVariable -Name $Name -Value $null -Target $EnvironmentVariableTarget.Machine
            SetEnvironmentVariable -Name $Name -Value $null -Target $EnvironmentVariableTarget.Process
        }
        catch 
        {
            Write-Verbose ($localizedData.EnvVarRemoveError -f $Name, $Value)

            throw $_
        }
    }
}


#------------------------------
# The Set-TargetResource cmdlet
#------------------------------
FUNCTION Set-TargetResource
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    param
    (       
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,
        
        [ValidateNotNull()]
        [System.String]
        $Value = [String]::Empty,
        
        [ValidateSet("Present", "Absent")]
        [System.String]
        $Ensure = "Present",
        
        [System.Boolean]
        $Path = $false
    )
    
    $ValueSpecified = $PSBoundParameters.ContainsKey("Value")    
    
    $curVarProperties = GetItemProperty $EnvVarRegPathMachine -Name $Name -Expand:(-not $Path) -ErrorAction SilentlyContinue
    $currentValueFromEnv = GetEnvironmentVariable -Name $name -Target $EnvironmentVariableTarget.Process

    # ----------------
    # ENSURE = PRESENT
    if ($Ensure -ieq "Present")
    {        
        if (($curVarProperties -eq $null) -or (($currentValueFromEnv -eq $null) -and ($curVarProperties.$Name -ne [string]::Empty)))  # The specified variable doesn't exist already
        {
            # Given the specified $Name environment variable doesn't exist already,
            # simply create one with the specified value and return. If no $Value is
            # specified, the default value is set to empty string "" (per spec).
            # Both path and non-path cases are covered by this.
            
            $successMessage = $localizedData.EnvVarCreated -f $Name, $Value

            if ($PSCmdlet.ShouldProcess($successMessage, $null, $null))
            {    
                Set-EnvVar -Name $Name -Value $Value
            }            
                        
            return
        }
        
        # If the control reaches here, the specified variable exists already

        if (!$ValueSpecified)
        {
            # Given no $Value was specified to be set and the variable exists,
            # we'll leave the existing variable as is.
            # This covers both path and non-path variables.

            Write-Log -Message ($localizedData.EnvVarUnchanged -f $Name, $curVarProperties.$Name)

            return
        }

        # If the control reaches here: the specified variable exists already and a $Value has been specified to be set.

        if (!$Path)
        {
            # For non-path variables, simply set the specified $Value as the new value of the specified
            # variable $Name, then return.

            $successMessage = $localizedData.EnvVarUpdated -f $Name, $curVarProperties.$Name, $Value
            if ($Value -ceq $curVarProperties.$Name)
            {
                $successMessage = $localizedData.EnvVarUnchanged -f $Name, $curVarProperties.$Name
            }

            if ($PSCmdlet.ShouldProcess($successMessage, $null, $null) -and ($Value -cne $curVarProperties.$Name))
            {    
                Set-EnvVar -Name $Name -Value $Value
            }             

            return
        }
        
        # If the control reaches here: the specified variable exists already, it is a path variable and a $Value has been specified to be set.
            
        # Check if an empty, whitespace or semi-colon only string has been specified. If yes, return unchanged.
        $trimmedValue = $Value.Trim(";"," ")
        if ([String]::IsNullOrEmpty($trimmedValue))
        {
            Write-Log -Message ($localizedData.EnvVarPathUnchanged -f $Name, $curVarProperties.$Name)

            return        
        }


        $setValue = $curVarProperties.$Name + ";"
        $specifiedPaths = $trimmedValue -split ";"
        $currentPaths = $curVarProperties.$Name -split ";"                                
        $varUpdated = $false

        foreach ($specifiedPath in $specifiedPaths)            
        {            
            if (FindSubPath -QueryPath $specifiedPath -PathList $currentPaths)
            {
                # Found this $specifiedPath as one of the $currentPaths, no need to add this again, skip/continue to the next $specifiedPath
                
                continue
            }

            # If the control reached here, we didn't find this $specifiedPath in the $currentPaths, add it
            # and mark the environment variable as updated.

            $varUpdated = $true
            $setValue += $specifiedPath + ";"                            
        }  

        # Remove any extraneous ";" at the end (and potentially start - as a side-effect) of the value to be set
        $setValue = $setValue.Trim(";")        
                                           
        # Set the expected success message
        $successMessage = $localizedData.EnvVarPathUnchanged -f $Name, $curVarProperties.$Name                   
        if ($varUpdated)
        {
            $successMessage = $localizedData.EnvVarPathUpdated -f $Name, $curVarProperties.$Name, $setValue
        }
                
        if ($PSCmdlet.ShouldProcess($successMessage, $null, $null))
        {    
            # Finally update the existing environment path variable

            Set-EnvVar -Name $Name -Value $setValue
        }        
    }

    # ---------------
    # ENSURE = ABSENT
    elseif ($Ensure -ieq "Absent")
    {
        if(($curVarProperties -eq $null) -and ($currentValueFromEnv -eq $null))
        {
            # Variable not found, condition is satisfied and there is nothing to set/remove, return

            Write-Log -Message ($localizedData.EnvVarNotFound -f $Name)
                        
            return
        }
        
        if(!$ValueSpecified -or !$Path)
        {
            # If no $Value specified to be removed, simply remove the environment variable (holds true for both path and non-path variables
            # OR
            # Regardless of $Value, if the target variable is a non-path variable, simply remove it to meet the absent condition

            $successMessage = $localizedData.EnvVarRemoved -f $Name

            if ($PSCmdlet.ShouldProcess($successMessage, $null, $null))
            {    
                Remove-EnvVar -Name $Name
            }             

            return
        }
                
        # If the control reaches here: target variable is an existing environment path-variable and a specified $Value needs be removed from it

        # Check if an empty string or semi-colon only string has been specified as $Value. If yes, return unchanged as we don't need to remove anything.
        $trimmedValue = $Value.Trim(";")
        if ([String]::IsNullOrEmpty($trimmedValue))
        {
            Write-Log -Message ($localizedData.EnvVarPathUnchanged -f $Name, $curVarProperties.$Name)

            return        
        }
                
        $finalPath = ""
        $specifiedPaths = $trimmedValue -split ";"
        $currentPaths = $curVarProperties.$Name -split ";"                                
        $varAltered = $false

        foreach ($subpath in $currentPaths)            
        {
            if (FindSubPath -QueryPath $subpath -PathList $specifiedPaths)
            {
                # Found this $subpath as one of the $specifiedPaths, skip adding this to the final value/path of this variable
                # and mark the variable as altered.

                $varAltered = $true
                continue
            }

            # If the control reaches here, the current $subpath was not part of the $specifiedPaths (to be removed),
            # so keep this $subpath in the finalPath
            
            $finalPath += $subpath + ";"                            
        }                          
        
        # Remove any extraneous ";" at the end (and potentially start - as a side-effect) of the $finalPath
        $finalPath = $finalPath.Trim(";")
                          
            
        # Set the expected success message
        $successMessage = $localizedData.EnvVarPathUnchanged -f $Name, $curVarProperties.$Name
        if ($varAltered)
        {
            $successMessage = $localizedData.EnvVarPathUpdated -f $Name, $curVarProperties.$Name, $finalPath
            
            if ([String]::IsNullOrEmpty($finalPath))
            {
                $successMessage = $localizedData.EnvVarRemoved -f $Name
            }            
        }
        
        # Handle WhatIf case and update resource as appropriate
        if ($PSCmdlet.ShouldProcess($successMessage, $null, $null))
        {    
            # Finally, update the environment path-variable

            if ([String]::IsNullOrEmpty($finalPath))
            {
                Remove-EnvVar -Name $Name
            }
            else
            {
                Set-EnvVar -Name $Name -Value $finalPath
            }

            if($err)
            {
                Write-Log -Message ($localizedData.EnvVarPathRemoveError -f $Value, $Name, $curVarProperties.$Name)

                throw $err
            }
        } 
    }
}


#-------------------------------
# The Test-TargetResource cmdlet
#-------------------------------
FUNCTION Test-TargetResource
{
    [OutputType([System.Boolean])]
    param
    (       
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,
        
        [ValidateNotNull()]
        [System.String]
        $Value,

        [ValidateSet("Present", "Absent")]
        [System.String]
        $Ensure = "Present",
        
        [System.Boolean]
        $Path = $false
    )
    
    $ValueSpecified = $PSBoundParameters.ContainsKey("Value")
    $curVarProperties = GetItemProperty $EnvVarRegPathMachine -Name $Name -Expand:(-not $Path) -ErrorAction SilentlyContinue
    $currentValueFromEnv = GetEnvironmentVariable -Name $name -Target $EnvironmentVariableTarget.Process

    # ----------------
    # ENSURE = PRESENT
    if ($Ensure -ieq "Present")
    {        
        if (($curVarProperties -eq $null) -or (($currentValueFromEnv -eq $null) -and ($curVarProperties.$Name -ne [string]::Empty)) )
        {
            # Variable not found, return failure

            Write-Verbose ($localizedData.EnvVarNotFound -f $Name)

            return $false
        }

        if (!$ValueSpecified)
        {
            # No value has been specified for test, so the existence of the variable means success

            Write-Verbose ($localizedData.EnvVarFound -f $Name, $curVarProperties.$Name)

            return $true
        }
        
        if (!$Path)
        {
            # For this non-path variable, make sure that the specified $Value matches the current value.
            # Success if it matches, failure otherwise

            if ($Value -ceq $curVarProperties.$Name)
            {
                Write-Verbose ($localizedData.EnvVarFound -f $Name, $curVarProperties.$Name)
                
                return $true                
            }
            else
            {
                Write-Verbose ($localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $curVarProperties.$Name, $Value)

                return $false
            }
        }             
                       
        # If the control reaches here, the expected environment variable exists, it is a path variable and a $Value is specified to test against
                
        if (FindPath -ExistingPaths $curVarProperties.$Name -QueryPaths $Value -FindCriteria All)
        {
            # The specified path was completely present in the existing environment variable, return success

            Write-Verbose ($localizedData.EnvVarFound -f $Name, $curVarProperties.$Name)

            return $true
        }   
                    
        # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure
                
        Write-Verbose ($localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $curVarProperties.$Name, $Value)

        return $false 
    }

    # ---------------
    # ENSURE = ABSENT
    elseif ($Ensure -eq "Absent")
    {
        if(($curVarProperties -eq $null) -and ($currentValueFromEnv -eq $null))
        {
            # Variable not found (path/non-path and $Value both do not matter then), return success

            Write-Verbose ($localizedData.EnvVarNotFound -f $Name)

            return $true
        }

        if (!$ValueSpecified)
        {
            # Given no value has been specified for test, the mere existence of the variable fails the test

            Write-Verbose ($localizedData.EnvVarFound -f $Name, $curVarProperties.$Name)

            return $false
        }

        # If the control reaches here: the variable exists and a value has been specified to test against it
                
        if (!$Path)
        {            
            # For this non-path variable, make sure that the specified value doesn't match the current value
            # Success if it doesn't match, failure otherwise
            
            if ($Value -cne $curVarProperties.$Name)
            {
                Write-Verbose ($localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $curVarProperties.$Name, $Value)                
                
                return $true                
            }
            else
            {
                Write-Verbose ($localizedData.EnvVarFound -f $Name, $curVarProperties.$Name)

                return $false
            }
        }
                    
        # If the control reaches here: the variable exists, it is a path variable, and a value has been specified to test against it
        
        if (FindPath -ExistingPaths $curVarProperties.$Name -QueryPaths $Value -FindCriteria Any)
        {
            # One of the specified paths in $Value exists in the environment variable path, thus the test fails

            Write-Verbose ($localizedData.EnvVarFound -f $Name, $curVarProperties.$Name)

            return $false
        }
                    
        # If the control reached here, none of the specified paths were found in the existing path-variable, return success

        Write-Verbose ($localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $curVarProperties.$Name, $Value)                

        return $true        
    }    
}


#----------------------------------------
# Utility to write WhatIf or Verbose logs
#----------------------------------------
FUNCTION Write-Log
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    param
    (   
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Message
    )

    if ($PSCmdlet.ShouldProcess($Message, $null, $null))
    {
        Write-Verbose $Message        
    }    
}


#-----------------------------------
# Utility to match environment paths
#-----------------------------------
FUNCTION FindPath
{    
    param
    (               
        [System.String]
        $ExistingPaths,
        
        [System.String]
        $QueryPaths,

        [parameter(Mandatory = $true)]      
        [ValidateSet("Any", "All")]
        [System.String]
        $FindCriteria
    )

    $existingPathList = $ExistingPaths -split ";"
    $queryPathList = $QueryPaths -split ";"

    switch ($FindCriteria)
    {
        "Any"
        {
            foreach ($queryPath in $queryPathList)
            {            
                if (FindSubPath -QueryPath $queryPath -PathList $existingPathList)
                {
                    # Found this $queryPath in the existing paths, return $true
                    return $true
                }                             
            }

            # If the control reached here, none of the $QueryPaths were found as part of the $ExistingPaths, return $false
            return $false   
        }

        "All"
        {
            foreach ($queryPath in $queryPathList)
            {
                $found = $false
                if($queryPath) 
                {
                    if (!(FindSubPath -QueryPath $queryPath -PathList $existingPathList))
                    {
                        # The current $queryPath wasn't found in any of the $existingPathList, return failure
                        return $false
                    }
                }                
            }

            # If the control reached here, all of the $QueryPaths were found as part of the $ExistingPaths, return $true
            return $true
        }    
    }
}


#---------------------------------------
# Utility to search a path in a pathlist
#---------------------------------------
FUNCTION FindSubPath
{    
    param
    (
        [System.String]
        $QueryPath,
                
        [String[]]
        $PathList
    )
    
    foreach ($path in $PathList)
    {
        if($QueryPath -ieq $path)
        {
            # If the query path matches any of the paths in $PathList, return $true
            return $true
        }                
    }     
    
    return $false        
}

#---------------------------------------------------------------
# Utility to get item property without expanding it if necessary
#---------------------------------------------------------------
FUNCTION GetItemProperty
{
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Path,
        
        [ValidateNotNull()]
        [System.String]
        $Name,
        
        [switch]
        $Expand = $false
    )

    if ($Expand)
    {
        return (Get-ItemProperty $EnvVarRegPathMachine -Name $Name -ErrorAction SilentlyContinue)
    }
    else
    {
        if (!(Test-Path -Path $Path))
        {
            return $null;
        }

        $PathTokens = $Path.Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)
        $Division = $PathTokens[0].Replace(':', '')
        $Entry = $PathTokens[1..($PathTokens.Count-1)] -join '\'
        
        # Since the target registry path coming to this function is hardcoded for local machine
        $Hive = [Microsoft.Win32.Registry]::LocalMachine

        $NoteProperties = @{}
        try
        {
            $Key = $Hive.OpenSubKey($Entry)
            
            $ValueNames = $Key.GetValueNames()
            if ($ValueNames -inotcontains $Name)
            {
                return $null
            }
            
            [string] $Value = $Key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
            $NoteProperties.Add($Name, $Value)
        }
        finally
        {
            if ($key)
            {
                $key.Close()
            }
        }

        [System.Management.Automation.PSObject] $PropertyResults = New-Object -TypeName System.Management.Automation.PSObject -Property $NoteProperties

        return $PropertyResults
    }
}

Export-ModuleMember -function Get-TargetResource, Set-TargetResource, Test-TargetResource