DscResources/MSFT_EnvironmentResource/MSFT_EnvironmentResource.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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
$errorActionPreference = 'Stop'
Set-StrictMode -Version 'Latest'

# Import CommonResourceHelper for Get-LocalizedData
$script:dscResourcesFolderFilePath = Split-Path $PSScriptRoot -Parent
$script:commonResourceHelperFilePath = Join-Path -Path $script:dscResourcesFolderFilePath -ChildPath 'CommonResourceHelper.psm1'
Import-Module -Name $script:commonResourceHelperFilePath

$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_EnvironmentResource'

$script:envVarRegPathMachine = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment'
$script:envVarRegPathUser = 'HKCU:\Environment'

$script:maxSystemEnvVariableLength = 1024
$script:maxUserEnvVariableLength = 255

<#
    .SYNOPSIS
        Retrieves the state of the environment variable. If both Machine and Process Target are
        specified, only the machine value will be returned.
 
    .PARAMETER Name
        The name of the environment variable to retrieve.
 
    .PARAMETER Target
        Indicates where to retrieve the variable: The machine or the process. If both are indicated
        then only the value from the machine is returned.
        The default is both since that is the default for the rest of the resource.
#>

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

        [Parameter()]
        [ValidateSet('Process', 'Machine')]
        [ValidateNotNullOrEmpty()]
        [System.String[]]
        $Target = ('Process', 'Machine')
    )

    $valueToReturn = $null

    if ($Target -contains 'Machine')
    {
        $environmentVaraible = Get-EnvironmentVariableWithoutExpanding -Name $Name -ErrorAction 'SilentlyContinue'

        if ($null -ne $environmentVaraible)
        {
            $valueToReturn = $environmentVaraible.$Name
        }
    }
    else
    {
        $valueToReturn = Get-ProcessEnvironmentVariable -Name $Name
    }

    $environmentResource = @{
        Name = $Name
        Value = $null
        Ensure = 'Absent'
    }

    if ($null -eq $valueToReturn)
    {
        Write-Verbose -Message ($script:localizedData.EnvVarNotFound -f $Name)
    }
    else
    {
        Write-Verbose -Message ($script:localizedData.EnvVarFound -f $Name, $valueToReturn)
        $environmentResource.Ensure = 'Present'
        $environmentResource.Value = $valueToReturn
    }

    return $environmentResource
}

<#
    .SYNOPSIS
        Creates, modifies, or removes an environment variable.
 
    .PARAMETER Name
        The name of the environment variable to create, modify, or remove.
 
    .PARAMETER Value
        The value to set the environment variable to.
        If a value is not provided, the variable cannot be created.
        If Ensure is set to Present, the variable does not already exist, and a value is not
        specified, an error will be thrown indicating that the variable cannot be created without
        a specified value. If Ensure is set to Present, the variable already exists, and no value
        is specified, nothing will be changed.
 
    .PARAMETER Ensure
        Specifies whether the variable should exist or not.
        To ensure that the variable or value does exist, set this property to Present.
        To ensure that the variable or value does not exist, set this property to Absent.
        The default value is Present.
 
    .PARAMETER Path
        Indicates whether or not this is a path variable. If this property is set to True,
        the value provided through the Value property will be appended to (or removed from if
        Ensure is set to Absent) the existing value.
        If this property is set to False, the existing value will be replaced by the new Value.
        The default value is False.
 
    .PARAMETER Target
        Indicates where to set the environment variable: The machine, the process, or both.
        The default is both: ('Process', 'Machine')
#>

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,

        [Parameter()]
        [ValidateNotNull()]
        [System.String]
        $Value = [System.String]::Empty,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.Boolean]
        $Path = $false,

        [Parameter()]
        [ValidateSet('Process', 'Machine')]
        [ValidateNotNullOrEmpty()]
        [System.String[]]
        $Target = ('Process', 'Machine')
    )

    $valueSpecified = ($Value -ne [System.String]::Empty)
    $currentValueFromMachine = $null
    $currentValueFromProcess = $null
    $currentPropertiesFromMachine = $null

    $setMachineVariable = ($Target -contains 'Machine')
    $setProcessVariable = ($Target -contains 'Process')

    if ($setMachineVariable)
    {
        if ($Path)
        {
            $currentPropertiesFromMachine = Get-EnvironmentVariableWithoutExpanding -Name $Name -ErrorAction 'SilentlyContinue'

            if ($null -ne $currentPropertiesFromMachine)
            {
                $currentValueFromMachine = $currentPropertiesFromMachine.$Name
            }
        }
        else
        {
            $currentPropertiesFromMachine = Get-ItemProperty -Path $script:envVarRegPathMachine -Name $Name -ErrorAction 'SilentlyContinue'
            $currentValueFromMachine = Get-EnvironmentVariable -Name $Name -Target 'Machine'
        }
    }

    if ($setProcessVariable)
    {
        $currentValueFromProcess = Get-EnvironmentVariable -Name $Name -Target 'Process'
    }

    # A different value of the environment variable needs to be displayed depending on the Target
    $currentValueToDisplay = ''
    if ($setMachineVariable -and $setProcessVariable)
    {
        $currentValueToDisplay = "Machine: $currentValueFromMachine, Process: $currentValueFromProcess"
    }
    elseif ($setMachineVariable)
    {
        $currentValueToDisplay = $currentValueFromMachine
    }
    else
    {
        $currentValueToDisplay = $currentValueFromProcess
    }

    if ($Ensure -eq 'Present')
    {
        $createMachineVariable = ((-not $setMachineVariable) -or ($null -eq $currentPropertiesFromMachine) -or ($currentValueFromMachine -eq [System.String]::Empty))
        $createProcessVariable = ((-not $setProcessVariable) -or ($null -eq $currentValueFromProcess) -or ($currentValueFromProcess -eq [System.String]::Empty))

        if ($createMachineVariable -and $createProcessVariable)
        {
            if (-not $valueSpecified)
            {
                <#
                    If the environment variable doesn't exist and no value is passed in
                    then there is nothing to set - so throw an error.
                #>


                New-InvalidOperationException -Message ($script:localizedData.CannotSetValueToEmpty -f $Name)
            }

            <#
                Given the specified $Name environment variable hasn't been created or set
                simply create one with the specified value and return.
                Both path and non-path cases are covered by this.
            #>


            Set-EnvironmentVariable -Name $Name -Value $Value -Target $Target

            Write-Verbose -Message ($script:localizedData.EnvVarCreated -f $Name, $Value)
            return
        }

        if (-not $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-Verbose -Message ($script:localizedData.EnvVarUnchanged -f $Name, $currentValueToDisplay)
            return
        }

        # Check if an empty, whitespace or semi-colon only string has been specified. If yes, return unchanged.
        $trimmedValue = $Value.Trim(';').Trim()

        if ([System.String]::IsNullOrEmpty($trimmedValue))
        {
            Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueToDisplay)
            return
        }

        if (-not $Path)
        {
            # For non-path variables, simply set the specified $Value as the new value of the specified
            # variable $Name for the given $Target

            if (($setMachineVariable -and ($Value -cne $currentValueFromMachine)) -or `
                ($setProcessVariable -and ($Value -cne $currentValueFromProcess)))
            {
                Set-EnvironmentVariable -Name $Name -Value $Value -Target $Target
                Write-Verbose -Message ($script:localizedData.EnvVarUpdated -f $Name, $currentValueToDisplay, $Value)
            }
            else
            {
                Write-Verbose -Message ($script:localizedData.EnvVarUnchanged -f $Name, $currentValueToDisplay)
            }

            return
        }

        # If the control reaches here, the specified variable exists, it is a path variable, and a value has been specified to be set.

        if ($setMachineVariable)
        {
            $valueUnchanged = Test-PathsInValue -ExistingPaths $currentValueFromMachine -QueryPaths $trimmedValue -FindCriteria 'All'

            if ($currentValueFromMachine -and -not $valueUnchanged)
            {
                $updatedValue = Add-PathsToValue -CurrentValue $currentValueFromMachine -NewValue $trimmedValue
                Set-EnvironmentVariable -Name $Name -Value $updatedValue -Target @('Machine')
                Write-Verbose -Message ($script:localizedData.EnvVarPathUpdated -f $Name, $currentValueFromMachine, $updatedValue)
            }
            else
            {
                Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueFromMachine)
            }
        }

        if ($setProcessVariable)
        {
            $valueUnchanged = Test-PathsInValue -ExistingPaths $currentValueFromProcess -QueryPaths $trimmedValue -FindCriteria 'All'

            if ($currentValueFromProcess -and -not $valueUnchanged)
            {
                $updatedValue = Add-PathsToValue -CurrentValue $currentValueFromProcess -NewValue $trimmedValue
                Set-EnvironmentVariable -Name $Name -Value $updatedValue -Target @('Process')
                Write-Verbose -Message ($script:localizedData.EnvVarPathUpdated -f $Name, $currentValueFromProcess, $updatedValue)
            }
            else
            {
                Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueFromProcess)
            }
        }
    }

    # Ensure = 'Absent'
    else
    {
        $machineVariableRemoved = ((-not $setMachineVariable) -or ($null -eq $currentPropertiesFromMachine))
        $processVariableRemoved = ((-not $setProcessVariable) -or ($null -eq $currentValueFromProcess))

        if ($machineVariableRemoved -and $processVariableRemoved)
        {
            # Variable not found, condition is satisfied and there is nothing to set/remove, return
            Write-Verbose -Message ($script:localizedData.EnvVarNotFound -f $Name)
            return
        }

        if ((-not $ValueSpecified) -or (-not $Path))
        {
            <#
                If $Value is not specified or if $Value is a non-path variable,
                simply remove the environment variable.
            #>


            Remove-EnvironmentVariable -Name $Name -Target $Target

            Write-Verbose -Message ($script:localizedData.EnvVarRemoved -f $Name)
            return
        }

        # 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(';').Trim()

        if ([System.String]::IsNullOrEmpty($trimmedValue))
        {
            Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueToDisplay)
            return
        }

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

        if ($setMachineVariable)
        {
            $finalPath = $null

            if ($currentValueFromMachine)
            {
                <#
                    If this value returns $null or an empty string, than the entire path should be removed.
                    If it returns the same value as the path that was passed in, than nothing needs to be
                    updated, otherwise, only the specified paths were removed but there are still others
                    that need to be left in, so the path variable is updated to remove only the specified paths.
                #>

                $finalPath = Remove-PathsFromValue -CurrentValue $currentValueFromMachine -PathsToRemove $trimmedValue
            }

            if ([System.String]::IsNullOrEmpty($finalPath))
            {
                Remove-EnvironmentVariable -Name $Name -Target @('Machine')
                Write-Verbose -Message ($script:localizedData.EnvVarRemoved -f $Name)
            }
            elseif ($finalPath -ceq $currentValueFromMachine)
            {
                Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueFromMachine)
            }
            else
            {
                Set-EnvironmentVariable -Name $Name -Value $finalPath -Target @('Machine')
                Write-Verbose -Message ($script:localizedData.EnvVarPathUpdated -f $Name, $currentValueFromMachine, $finalPath)
            }
        }

        if ($setProcessVariable)
        {
            $finalPath = $null

            if ($currentValueFromProcess)
            {
                <#
                    If this value returns $null or an empty string, than the entire path should be removed.
                    If it returns the same value as the path that was passed in, than nothing needs to be
                    updated, otherwise, only the specified paths were removed but there are still others
                    that need to be left in, so the path variable is updated to remove only the specified paths.
                #>

                $finalPath = Remove-PathsFromValue -CurrentValue $currentValueFromProcess -PathsToRemove $trimmedValue
            }

            if ([System.String]::IsNullOrEmpty($finalPath))
            {
                Remove-EnvironmentVariable -Name $Name -Target @('Process')
                Write-Verbose -Message ($script:localizedData.EnvVarRemoved -f $Name)
            }
            elseif ($finalPath -ceq $currentValueFromProcess)
            {
                Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueFromProcess)
            }
            else
            {
                Set-EnvironmentVariable -Name $Name -Value $finalPath -Target @('Process')
                Write-Verbose -Message ($script:localizedData.EnvVarPathUpdated -f $Name, $currentValueFromProcess, $finalPath)
            }
        }
    }
}

<#
    .SYNOPSIS
        Tests if the environment variable is in the desired state.
 
    .PARAMETER Name
        The name of the environment variable to test.
 
    .PARAMETER Value
        The value of the environment variable to test. If no value is specified then only the
        existence of the variable will be checked.
 
    .PARAMETER Ensure
        Specifies whether the variable should exist or not.
        To test that the variable does exist, set this property to Present.
        To test that the variable does not exist, set this property to Absent.
        The default value is Present.
 
    .PARAMETER Path
        Indicates whether or not this is a path variable. If this property is set to True,
        the value(s) provided through the Value property will be checked against all existing
        values already set in this variable.
        If this property is set to False, the value will be compared directly to the existing value.
        The default value is False.
 
    .PARAMETER Target
        Indicates where to test the environment variable: The machine, the process, or both.
        The default is both: ('Process', 'Machine')
#>

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

        [Parameter()]
        [ValidateNotNull()]
        [System.String]
        $Value,

        [Parameter()]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [Parameter()]
        [System.Boolean]
        $Path = $false,

        [Parameter()]
        [ValidateSet('Process', 'Machine')]
        [ValidateNotNullOrEmpty()]
        [System.String[]]
        $Target = ('Process', 'Machine')
    )

    $valueSpecified = $PSBoundParameters.ContainsKey('Value') -and ($Value -ne [System.String]::Empty)
    $currentValueFromMachine = $null
    $currentValueFromProcess = $null
    $currentPropertiesFromMachine = $null

    $checkMachineTarget = ($Target -contains 'Machine')
    $checkProcessTarget = ($Target -contains 'Process')

    if ($checkMachineTarget)
    {
        if ($Path)
        {
            $currentPropertiesFromMachine = Get-EnvironmentVariableWithoutExpanding -Name $Name -ErrorAction 'SilentlyContinue'

            if ($null -ne $currentPropertiesFromMachine)
            {
                $currentValueFromMachine = $currentPropertiesFromMachine.$Name
            }
        }
        else
        {
            $currentPropertiesFromMachine = Get-ItemProperty -Path $script:envVarRegPathMachine -Name $Name -ErrorAction 'SilentlyContinue'
            $currentValueFromMachine = Get-EnvironmentVariable -Name $Name -Target 'Machine'
        }
    }

    if ($checkProcessTarget)
    {
        $currentValueFromProcess = Get-EnvironmentVariable -Name $Name -Target 'Process'
    }

    # A different value of the environment variable needs to be displayed depending on the Target
    $currentValueToDisplay = ''
    if ($checkMachineTarget -and $checkProcessTarget)
    {
        $currentValueToDisplay = "Machine: $currentValueFromMachine, Process: $currentValueFromProcess"
    }
    elseif ($checkMachineTarget)
    {
        $currentValueToDisplay = $currentValueFromMachine
    }
    else
    {
        $currentValueToDisplay = $currentValueFromProcess
    }

    if (($checkMachineTarget -and ($null -eq $currentPropertiesFromMachine)) -or ($checkProcessTarget -and ($null -eq $currentValueFromProcess)))
    {
        # Variable not found
        Write-Verbose ($script:localizedData.EnvVarNotFound -f $Name)
        return ($Ensure -eq 'Absent')
    }

    if (-not $valueSpecified)
    {
        Write-Verbose ($script:localizedData.EnvVarFound -f $Name, $currentValueToDisplay)
        return ($Ensure -eq 'Present')
    }

    if (-not $Path)
    {
        # For this non-path variable, make sure that the specified $Value matches the current value.

        if (($checkMachineTarget -and ($Value -cne $currentValueFromMachine)) -or `
           ($checkProcessTarget -and ($Value -cne $currentValueFromProcess)))
        {
            Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value)
            return ($Ensure -eq 'Absent')
        }
        else
        {
            Write-Verbose ($script:localizedData.EnvVarFound -f $Name, $currentValueToDisplay)
            return ($Ensure -eq 'Present')
        }
    }

    # If the control reaches here, the expected environment variable exists, it is a path variable and a $Value is specified to test against
    if ($Ensure -eq 'Present')
    {
        if ($checkMachineTarget)
        {
            if (-not (Test-PathsInValue -ExistingPaths $currentValueFromMachine -QueryPaths $Value -FindCriteria 'All'))
            {
                # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure
                Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value)
                return $false
            }
        }

        if ($checkProcessTarget)
        {
            if (-not (Test-PathsInValue -ExistingPaths $currentValueFromProcess -QueryPaths $Value -FindCriteria 'All'))
            {
                # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure
                Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value)
                return $false
            }
        }

        # The specified path was completely present in the existing environment variable, return success
        Write-Verbose ($script:localizedData.EnvVarFound -f $Name, $currentValueToDisplay)
        return $true
    }
    # Ensure = 'Absent'
    else
    {
        if ($checkMachineTarget)
        {
            if (Test-PathsInValue -ExistingPaths $currentValueFromMachine -QueryPaths $Value -FindCriteria 'Any')
            {
                # One of the specified paths in $Value exists in the environment variable path, thus the test fails
                Write-Verbose ($script:localizedData.EnvVarFound -f $Name, $currentValueFromMachine)
                return $false
            }
        }

        if ($checkProcessTarget)
        {
            if (Test-PathsInValue -ExistingPaths $currentValueFromProcess -QueryPaths $Value -FindCriteria 'Any')
            {
                # One of the specified paths in $Value exists in the environment variable path, thus the test fails
                Write-Verbose ($script:localizedData.EnvVarFound -f $Name, $currentValueFromProcess)
                return $false
            }
        }

        # If the control reached here, none of the specified paths were found in the existing path-variable, return success
        Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value)
        return $true
    }
}

<#
    .SYNOPSIS
        Retrieves the value of the environment variable from the given Target.
 
    .PARAMETER Name
        The name of the environment variable to retrieve the value from.
 
    .PARAMETER Target
        Indicates where to retrieve the environment variable from. Currently, only
        Process and Machine are being used, but User is included for future extension
        of this resource.
#>

function Get-EnvironmentVariable
{
    [CmdletBinding()]
    [OutputType([System.String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Process', 'Machine')]
        [System.String]
        $Target
    )

    $valueToReturn = $null

    if ($Target -eq 'Process')
    {
        $valueToReturn = Get-ProcessEnvironmentVariable -Name $Name
    }
    elseif ($Target -eq 'Machine')
    {
        $retrievedProperty = Get-ItemProperty -Path $script:envVarRegPathMachine -Name $Name -ErrorAction 'SilentlyContinue'

        if ($null -ne $retrievedProperty)
        {
            $valueToReturn = $retrievedProperty.$Name
        }
    }
    elseif ($Target -eq 'User')
    {
        $retrievedProperty = Get-ItemProperty -Path $script:envVarRegPathUser -Name $Name -ErrorAction 'SilentlyContinue'

        if ($null -ne $retrievedProperty)
        {
            $valueToReturn = $retrievedProperty.$Name
        }
    }

    return $valueToReturn
}

<#
    .SYNOPSIS
        Wrapper function to retrieve an environment variable from the current process.
 
    .PARAMETER Name
        The name of the variable to retrieve
#>

function Get-ProcessEnvironmentVariable
{
    [CmdletBinding()]
    [OutputType([System.String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name
    )

    return [System.Environment]::GetEnvironmentVariable($Name)
}

<#
    .SYNOPSIS
        If there are any paths in NewPaths that aren't in CurrentValue they will be added
        to the current paths value and a String will be returned containing all old paths
        and new paths. Otherwise the original value will be returned unchanged.
 
    .PARAMETER CurrentValue
        A semicolon-separated String containing the current path values.
 
    .PARAMETER NewPaths
        A semicolon-separated String containing any paths that should be added to
        the current value. If CurrentValue already contains a path, it will not be added.
#>

function Add-PathsToValue
{
    [CmdletBinding()]
    [OutputType([System.String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CurrentValue,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $NewValue
    )

    $finalValue = $CurrentValue + ';'
    $currentPaths = $CurrentValue -split ';'
    $newPaths = $NewValue -split ';'

    foreach ($path in $newPaths)
    {
        if ($currentPaths -notcontains $path)
        {
            <#
                If the control reached here, we didn't find this $specifiedPath in the $currentPaths,
                so add it.
            #>


            $finalValue += ($path + ';')
        }
    }

    # Remove any extraneous ';' at the end (and potentially start - as a side-effect) of the value to be set
    return $finalValue.Trim(';')
}

<#
    .SYNOPSIS
        If there are any paths in PathsToRemove that aren't in CurrentValue they will be removed
        from the current paths value and either the new value will be returned if there are still
        paths that remain, or an empty string will be returned if all paths were removed.
        If none of the paths in PathsToRemove are in CurrentValue then this function will
        return CurrentValue since nothing needs to be changed.
 
    .PARAMETER CurrentValue
        A semicolon-separated String containing the current path values.
 
    .PARAMETER PathsToRemove
        A semicolon-separated String containing any paths that should be removed from
        the current value.
#>

function Remove-PathsFromValue
{
    [OutputType([System.String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CurrentValue,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $PathsToRemove
    )

    $finalPath = ''
    $specifiedPaths = $PathsToRemove -split ';'
    $currentPaths = $CurrentValue -split ';'
    $varAltered = $false

    foreach ($subpath in $currentPaths)
    {
        if ($specifiedPaths -contains $subpath)
        {
            <#
                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
        }
        else
        {
            # 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(';')

    if ($varAltered)
    {
        return $finalPath
    }
    else
    {
        return $CurrentValue
    }
}

<#
    .SYNOPSIS
        Sets the value of the environment variable with the given name if a value is specified.
        If no value is specified, then the environment variable will be removed.
 
    .PARAMETER Name
        The name of the environment variable to set or remove.
 
    .PARAMETER Value
        The value to set the environment variable to. If not provided, then the variable will
        be removed.
 
    .PARAMETER Target
        Indicates where to set or remove the environment variable: The machine, the process, or both.
        The logic for User is also included here for future expansion of this resource.
#>

function Set-EnvironmentVariable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,

        [Parameter()]
        [System.String]
        $Value,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Process', 'Machine')]
        [System.String[]]
        $Target
    )

    $valueSpecified = $PSBoundParameters.ContainsKey('Value')

    try
    {
        # If the Value is set to [System.String]::Empty then nothing should be updated for the process
        if (($Target -contains 'Process') -and (-not $valueSpecified -or ($Value -ne [System.String]::Empty)))
        {
            if (-not $valueSpecified)
            {
                Set-ProcessEnvironmentVariable -Name $Name -Value $null
            }
            else
            {
                Set-ProcessEnvironmentVariable -Name $Name -Value $Value
            }
        }

        if ($Target -contains 'Machine')
        {
            if ($Name.Length -ge $script:maxSystemEnvVariableLength)
            {
                New-InvalidArgumentException -Message $script:localizedData.ArgumentTooLong -ArgumentName $Name
            }

            $path = $script:envVarRegPathMachine

            if (-not $valueSpecified)
            {
                $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue'

                if ($environmentKey)
                {
                    Remove-ItemProperty -Path $path -Name $Name
                }
                else
                {
                    $message = ($script:localizedData.RemoveNonExistentVarError -f $Name)
                    New-InvalidArgumentException -Message $message -ArgumentName $Name
                }
            }
            else
            {
                Set-ItemProperty -Path $path -Name $Name -Value $Value
                $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue'

                if ($null -eq $environmentKey)
                {
                    $message = ($script:localizedData.GetItemPropertyFailure -f $Name, $path)
                    New-InvalidArgumentException -Message $message -ArgumentName $Name
                }
            }
        }

        # The User feature of this resource is not yet implemented.
        if ($Target -contains 'User')
        {
            if ($Name.Length -ge $script:maxUserEnvVariableLength)
            {
                New-InvalidArgumentException -Message $script:localizedData.ArgumentTooLong -ArgumentName $Name
            }

            $path = $script:envVarRegPathUser

            if (-not $valueSpecified)
            {
                $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue'

                if ($environmentKey)
                {
                    Remove-ItemProperty -Path $path -Name $Name
                }
                else
                {
                    $message = ($script:localizedData.RemoveNonExistentVarError -f $Name)
                    New-InvalidArgumentException -Message $message -ArgumentName $Name
                }
            }
            else
            {
                Set-ItemProperty -Path $path -Name $Name -Value $Value
                $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue'

                if ($null -eq $environmentKey)
                {
                    $message = ($script:localizedData.GetItemPropertyFailure -f $Name, $path)
                    New-InvalidArgumentException -Message $message -ArgumentName $Name
                }
            }
        }
    }
    catch
    {
        New-InvalidOperationException -Message ($script:localizedData.EnvVarSetError -f $Name, $Value) `
                                      -ErrorRecord $_
    }

}

<#
    .SYNOPSIS
        Wrapper function to set an environment variable for the current process.
 
    .PARAMETER Name
        The name of the environment variable to set.
 
    .PARAMETER Value
        The value to set the environment variable to.
#>

function Set-ProcessEnvironmentVariable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,

        [Parameter()]
        [System.String]
        $Value = [System.String]::Empty
    )

    [System.Environment]::SetEnvironmentVariable($Name, $Value)
}

<#
    .SYNOPSIS
        Removes an environment variable from the given target(s) by calling Set-EnvironmentVariable
        with no Value specified.
 
    .PARAMETER Name
        The name of the environment variable to remove.
 
    .PARAMETER Target
        Indicates where to remove the environment variable from: The machine, the process, or both.
#>

function Remove-EnvironmentVariable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Name,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Process', 'Machine')]
        [System.String[]]
        $Target
    )

    try
    {
        Set-EnvironmentVariable -Name $Name -Target $Target
    }
    catch
    {
        New-InvalidOperationException -Message ($script:localizedData.EnvVarRemoveError -f $Name) `
                                      -ErrorRecord $_
    }
}

<#
    .SYNOPSIS
        Tests all of the paths in QueryPaths against those in ExistingPaths.
        If FindCriteria is set to 'All' then it will only return True if all of the
        paths in QueryPaths are in ExistingPaths, otherwise it will return False.
        If FindCriteria is set to 'Any' then it will return True if any of the paths
        in QueryPaths are in ExistingPaths, otherwise it will return False.
 
    .PARAMETER ExistingPaths
        A semicolon-separated String containing the path values to test against.
 
    .PARAMETER QueryPaths
        A semicolon-separated String containing the path values to ensure are either
        included or not included in ExistingPaths.
 
    .PARAMETER FindCriteria
        Set to either 'All' or 'Any' to indicate whether all of the paths in QueryPaths
        should be included in ExistingPaths or any of them.
#>

function Test-PathsInValue
{
    [OutputType([System.Boolean])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $ExistingPaths,

        [Parameter(Mandatory = $true)]
        [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 ($existingPathList -contains $queryPath)
                {
                    # Found this $queryPath in the existing paths, return $true
                    return $true
                }
            }

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

        'All'
        {
            foreach ($queryPath in $queryPathList)
            {
                if ($queryPath)
                {
                    if ($existingPathList -notcontains $queryPath)
                    {
                        # The current $queryPath wasn't found in any of the $existingPathList, return false
                        return $false
                    }
                }
            }

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

<#
    .SYNOPSIS
        Retrieves the Environment variable with the given name from the registry on the machine.
        It returns the result as an object containing a Hashtable with the environment variable
        name and its current value on the machine. This is to most closely represent what the
        actual API call returns. If an environment variable with the given name is not found, then
        $null will be returned.
 
    .PARAMETER Name
        The name of the environment variable to retrieve the value of.
#>

function Get-EnvironmentVariableWithoutExpanding
{
    [OutputType([System.Management.Automation.PSObject])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [System.String]
        $Name
    )

    $path = $script:envVarRegPathMachine
    $pathTokens = $path.Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)
    $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
        }

        [System.String] $value = Get-KeyValue -Name $Name -Key $key
        $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
}

<#
    .SYNOPSIS
        Wrapper function to get the value of the environment variable with the given name
        from the specified registry key.
 
    .PARAMETER Name
        The name of the environment variable to retrieve the value of.
 
    .PARAMETER Key
        The key to retrieve the environment variable from.
#>

function Get-KeyValue
{
    [OutputType([System.String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [System.String]
        $Name,

        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [Microsoft.Win32.RegistryKey]
        $Key
    )

    return $Key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
}