Modules/ComputerManagementDsc.Common/ComputerManagementDsc.Common.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
$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules'
Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common')

# Import Localization Strings
$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US'

<#
    .SYNOPSIS
        This function tests if a cmdlet exists.
 
    .PARAMETER Name
        The name of the cmdlet to check for.
 
    .PARAMETER Module
        The module containing the command.
#>

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

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

    return ($null -ne (Get-Command @PSBoundParameters -ErrorAction SilentlyContinue))
} # function Test-Command

<#
    .SYNOPSIS
        Get the of the current time zone Id.
 
    .NOTES
        This function is also used by ScheduledTask integration tests.
#>

function Get-TimeZoneId
{
    [CmdletBinding()]
    param
    (
    )

    if (Test-Command -Name 'Get-TimeZone' -Module 'Microsoft.PowerShell.Management')
    {
        Write-Verbose -Message ($script:localizedData.GettingTimeZoneMessage -f 'Cmdlets')

        $timeZone = (Get-TimeZone).StandardName
    }
    else
    {
        Write-Verbose -Message ($script:localizedData.GettingTimeZoneMessage -f 'CIM')

        $timeZone = (Get-CimInstance `
                -ClassName Win32_TimeZone `
                -Namespace root\cimv2).StandardName
    }

    Write-Verbose -Message ($script:localizedData.CurrentTimeZoneMessage -f $timeZone)

    $timeZoneInfo = [System.TimeZoneInfo]::GetSystemTimeZones() |
    Where-Object -Property StandardName -EQ $timeZone

    return $timeZoneInfo.Id
} # function Get-TimeZoneId

<#
    .SYNOPSIS
        Compare a time zone Id with the current time zone Id.
 
    .PARAMETER TimeZoneId
        The Id of the time zone to compare with the current time zone.
 
    .NOTES
        This function is also used by ScheduledTask integration tests.
#>

function Test-TimeZoneId
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $TimeZoneId
    )

    # Test if the expected value is the same as the current value.
    $currentTimeZoneId = Get-TimeZoneId

    return $TimeZoneId -eq $currentTimeZoneId
} # function Test-TimeZoneId

<#
    .SYNOPSIS
        Sets the current time zone using a time zone Id.
 
    .PARAMETER TimeZoneId
        The Id of the time zone to set.
 
    .NOTES
        This function is also used by ScheduledTask integration tests.
#>

function Set-TimeZoneId
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $TimeZoneId
    )

    if (Test-Command -Name 'Set-TimeZone' -Module 'Microsoft.PowerShell.Management')
    {
        Set-TimeZone -Id $TimeZoneId
    }
    else
    {
        if (Test-Command -Name 'Add-Type' -Module 'Microsoft.Powershell.Utility')
        {
            # We can use reflection to modify the time zone.
            Write-Verbose -Message ($script:localizedData.SettingTimeZoneMessage -f $TimeZoneId, '.NET')

            Set-TimeZoneUsingDotNet -TimeZoneId $TimeZoneId
        }
        else
        {
            # For anything else use TZUTIL.EXE.
            Write-Verbose -Message ($script:localizedData.SettingTimeZoneMessage -f $TimeZoneId, 'TZUTIL.EXE')

            try
            {
                & tzutil.exe @('/s', $TimeZoneId)
            }
            catch
            {
                Write-Verbose -Message $_.Exception.Message
            } # try
        } # if
    } # if

    Write-Verbose -Message ($script:localizedData.TimeZoneUpdatedMessage -f $TimeZoneId)
} # function Set-TimeZoneId

<#
    .SYNOPSIS
        This function sets the time zone on the machine using .NET reflection.
        It exists so that the ::Set method can be mocked by Pester.
 
    .PARAMETER TimeZoneId
        The Id of the time zone to set using .NET.
 
    .NOTES
        This function is also used by ScheduledTask integration tests.
#>

function Set-TimeZoneUsingDotNet
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $TimeZoneId
    )

    # Add the [TimeZoneHelper.TimeZone] type if it is not defined.
    if (-not ([System.Management.Automation.PSTypeName] 'TimeZoneHelper.TimeZone').Type)
    {
        Write-Verbose -Message ($script:localizedData.AddingSetTimeZoneDotNetTypeMessage)

        $setTimeZoneCs = Get-Content `
            -Path (Join-Path -Path $PSScriptRoot -ChildPath 'SetTimeZone.cs') `
            -Raw

        Add-Type `
            -Language CSharp `
            -TypeDefinition $setTimeZoneCs
    } # if

    [Microsoft.PowerShell.TimeZone.TimeZone]::Set($TimeZoneId)
} # function Set-TimeZoneUsingDotNet

<#
    .SYNOPSIS
        This function gets a specific power plan or all available power plans.
        The function returns one or more hashtable(s) containing
        the friendly name and GUID of the power plan(s).
 
    .PARAMETER PowerPlan
        Friendly name or GUID of a power plan to get.
        When not specified the function will return all available power plans.
 
    .NOTES
        This function is used by the PowerPlan resource.
#>

function Get-PowerPlan
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable[]])]
    param
    (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $PowerPlan
    )

    $ErrorActionPreference = 'Stop'

    # Get all available power plan(s) as a hashtable with friendly name and GUID
    $allAvailablePowerPlans = Get-PowerPlanUsingPInvoke

    # If a specific power plan is specified filter for it otherwise return all
    if ($PSBoundParameters.ContainsKey('PowerPlan'))
    {
        $selectedPowerPlan = $allAvailablePowerPlans | Where-Object -FilterScript {
            ($_.FriendlyName -eq $PowerPlan) -or
            ($_.Guid -eq $PowerPlan)
        }

        return $selectedPowerPlan
    }
    else
    {
        return $allAvailablePowerPlans
    }
}

<#
    .SYNOPSIS
        This function gets the friendly name of a power plan specified by its GUID.
 
    .PARAMETER PowerPlanGuid
        The GUID of a power plan.
 
    .NOTES
        This function uses Platform Invoke (P/Invoke) mechanism to call native Windows APIs
        because the Win32_PowerPlan WMI class has issues on some platforms or is unavailable at all.
        e.g Server 2012 R2 core or Nano Server.
        This function is used by the Get-PowerPlan function.
#>

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

    $ErrorActionPreference = 'Stop'

    # Define C# signature of PowerReadFriendlyName function
    $MethodDefinition = @'
        [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]
        public static extern uint PowerReadFriendlyName(
            IntPtr RootPowerKey,
            Guid SchemeGuid,
            IntPtr SubGroupOfPowerSettingGuid,
            IntPtr PowerSettingGuid,
            IntPtr Buffer,
            ref uint BufferSize
        );
'@


    # Create Win32PowerReadFriendlyName object with the static method PowerReadFriendlyName.
    $powerprof = Add-Type `
        -MemberDefinition $MethodDefinition `
        -Name 'Win32PowerReadFriendlyName' `
        -Namespace 'Win32Functions' `
        -PassThru

    # Define variable for buffer size which whe have frist to figure out.
    $bufferSize = 0
    $returnCode = 0

    try
    {
        <#
            Frist get needed buffer size by calling PowerReadFriendlyName
            with NULL value for 'Buffer' parameter to get the required buffer size.
        #>

        $returnCode = $powerprof::PowerReadFriendlyName(
            [System.IntPtr]::Zero,
            $PowerPlanGuid,
            [System.IntPtr]::Zero,
            [System.IntPtr]::Zero,
            [System.IntPtr]::Zero,
            [ref]$bufferSize)

        if ($returnCode -eq 0)
        {
            try
            {
                # Now lets allocate the needed buffer size
                $ptrName = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Int32]$bufferSize)

                <#
                    Get the actual friendly name of the powerlan by calling PowerReadFriendlyName again.
                    This time with the correct buffer size for the 'Buffer' parameter.
                #>

                $returnCode = $powerprof::PowerReadFriendlyName(
                    [System.IntPtr]::Zero,
                    $PowerPlanGuid,
                    [System.IntPtr]::Zero,
                    [System.IntPtr]::Zero,
                    $ptrName,
                    [ref]$bufferSize)

                if ($returnCode -eq 0)
                {
                    # Create a managed String object form the unmanged memory block.
                    $friendlyName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptrName)
                    return $friendlyName
                }
                else
                {
                    throw [ComponentModel.Win32Exception]::new([System.Int32]$returnCode)
                }
            }
            finally
            {
                # Make sure allocated memory is freed up again.
                [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptrName)
            }
        }
        else
        {
            throw [ComponentModel.Win32Exception]::new([System.Int32]$returnCode)
        }
    }
    catch
    {
        New-InvalidOperationException `
            -Message ($script:localizedData.UnableToGetPowerSchemeFriendlyName -f $PowerPlanGuid, $_.Exception.NativeErrorCode, $_.Exception.Message)
    }
}

<#
    .SYNOPSIS
        This function gets the GUID of the currently active power plan.
 
    .NOTES
        This function uses Platform Invoke (P/Invoke) mechanism to call native Windows APIs
        because the Win32_PowerPlan WMI class has issues on some platforms or is unavailable at all.
        e.g Server 2012 R2 core or Nano Server.
        This function is used by the PowerPlan resource.
#>

function Get-ActivePowerPlan
{
    [CmdletBinding()]
    [OutputType([System.Guid])]
    param
    (
    )

    $ErrorActionPreference = 'Stop'

    # Define C# signature of PowerGetActiveScheme function
    $powerGetActiveSchemeDefinition = @'
        [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]
        public static extern uint PowerGetActiveScheme(IntPtr UserRootPowerKey, ref IntPtr ActivePolicyGuid);
'@


    $returnCode = 0

    # Create Win32PowerGetActiveScheme object with the static method PowerGetActiveScheme
    $powrprof = Add-Type `
        -MemberDefinition $powerGetActiveSchemeDefinition `
        -Name 'Win32PowerGetActiveScheme' `
        -Namespace 'Win32Functions' `
        -PassThru

    try
    {
        # Get the GUID of the active power scheme
        $activeSchemeGuid = [System.IntPtr]::Zero
        $returnCode = $powrprof::PowerGetActiveScheme([System.IntPtr]::Zero, [ref]$activeSchemeGuid)

        # Check for non 0 return codes / errors form the native function
        if ($returnCode -ne 0)
        {
            # Create a Win32Exception object out of the return code
            $win32Exception = ([ComponentModel.Win32Exception]::new([System.Int32]$returnCode))
            New-InvalidOperationException `
                -Message ($script:localizedData.FailedToGetActivePowerScheme -f $win32Exception.NativeErrorCode, $win32Exception.Message)
        }

        # Create a managed Guid object form the unmanged memory block and return it
        return [System.Runtime.InteropServices.Marshal]::PtrToStructure($activeSchemeGuid, [System.Type][System.Guid])
    }
    finally
    {
        # Make sure allocated memory is freed up again.
        [System.Runtime.InteropServices.Marshal]::FreeHGlobal($activeSchemeGuid)
    }
}

<#
    .SYNOPSIS
        This function enumerates all available power plans/schemes.
        The function returns one or more hashtable(s) containing
        the friendly name and GUID of the power plan(s).
 
    .NOTES
        This function uses Platform Invoke (P/Invoke) mechanism to call native Windows APIs
        because the Win32_PowerPlan WMI class has issues on some platforms or is unavailable at all.
        e.g Server 2012 R2 core or Nano Server.
        This function is used by the PowerPlan resource.
#>

function Get-PowerPlanUsingPInvoke
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable[]])]
    param
    (
    )

    $ErrorActionPreference = 'Stop'

    Write-Verbose -Message ($script:localizedData.EnumeratingPowerPlans)

    # Define C# signature of PowerEnumerate function
    $powerEnumerateDefinition = @'
        [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]
        public static extern uint PowerEnumerate(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            IntPtr SubGroupOfPowerSetting,
            int AccessFlags,
            uint Index,
            IntPtr rBuffer,
            ref uint BufferSize
        );
'@


    # Create Win32PowerEnumerate object with the static method PowerEnumerate
    $powrprof = Add-Type `
        -MemberDefinition $powerEnumerateDefinition `
        -Name 'Win32PowerEnumerate' `
        -Namespace 'Win32Functions' `
        -PassThru

    $index = 0
    $returnCode = 0
    $allAvailablePowerPlans = [System.Collections.ArrayList]::new()

    # PowerEnumerate returns the GUID of the powerplan(s). Guid = 16 Bytes.
    $bufferSize = 16

    <#
        The PowerEnumerate function returns only one guid at a time.
        So we have to loop here until error code 259 (no more data) is returned to get all power plan GUIDs.
    #>

    while ($returnCode -ne 259)
    {
        try
        {
            # Allocate buffer
            $readBuffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Int32]$bufferSize)

            # Get Guid of the power plan using the native PowerEnumerate function
            $returnCode = $powrprof::PowerEnumerate([System.IntPtr]::Zero, [System.IntPtr]::Zero, [System.IntPtr]::Zero, 16, $index, $readBuffer, [ref]$bufferSize)

            # Return Code 259 means no more data so we stop here.
            if ($returnCode -eq 259)
            {
                break
            }

            # Check for non 0 return codes / errors form the native function.
            if ($returnCode -ne 0)
            {
                # Create a Win32Exception object out of the return code
                $win32Exception = ([ComponentModel.Win32Exception]::new([System.Int32]$returnCode))
                New-InvalidOperationException `
                    -Message ($script:localizedData.UnableToEnumeratingPowerSchemes -f $win32Exception.NativeErrorCode, $win32Exception.Message)
            }

            # Create a managed Guid object form the unmanaged memory block
            $planGuid = [System.Runtime.InteropServices.Marshal]::PtrToStructure($readBuffer, [System.Type][System.Guid])

            Write-Verbose -Message ($script:localizedData.PowerPlanFound -f $planGuid)

            # Now get the friendly name of to the power plan
            $planFriendlyName = Get-PowerPlanFriendlyName -PowerPlanGuid $planGuid

            Write-Verbose -Message ($script:localizedData.PowerPlanFriendlyNameFound -f $planFriendlyName)

            $null = $allAvailablePowerPlans.Add(
                @{
                    FriendlyName = $planFriendlyName
                    Guid         = $planGuid
                }
            )

            $index++
        }
        finally
        {
            # Free up memory
            [System.Runtime.InteropServices.Marshal]::FreeHGlobal($readBuffer)
        }
    }

    Write-Verbose -Message ($script:localizedData.AllPowerPlansFound)

    return $allAvailablePowerPlans
}

<#
    .SYNOPSIS
        This function activates a specific power plan (specified by its GUID).
 
    .PARAMETER Guid
        GUID of a power plan to activate.
 
    .NOTES
        This function uses Platform Invoke (P/Invoke) mechanism to call native Windows APIs
        because the Win32_PowerPlan WMI class has on some platforms issues or is unavailable at all.
        e.g Server 2012 R2 core or Nano Server.
        This function is used by the Get-PowerPlan function respectively the PowerPlan resource.
#>

function Set-ActivePowerPlan
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.Guid]
        $PowerPlanGuid
    )

    $ErrorActionPreference = 'Stop'

    # Define C# signature of PowerSetActiveScheme function
    $powerSetActiveSchemeDefinition = @'
        [DllImport("powrprof.dll", CharSet = CharSet.Auto)]
        public static extern uint PowerSetActiveScheme(
            IntPtr RootPowerKey,
            Guid SchemeGuid
        );
'@


    # Create Win32PowerSetActiveScheme object with the static method PowerSetActiveScheme.
    $powrprof = Add-Type `
        -MemberDefinition $powerSetActiveSchemeDefinition `
        -Name 'Win32PowerSetActiveScheme' `
        -Namespace 'Win32Functions' `
        -PassThru

    try
    {
        # Set the active power scheme with the native function
        $returnCode = $powrprof::PowerSetActiveScheme([System.IntPtr]::Zero, $PowerPlanGuid)

        # Check for non 0 return codes / errors form the native function
        if ($returnCode -ne 0)
        {
            throw [ComponentModel.Win32Exception]::new([int]$returnCode)
        }
    }
    catch
    {
        New-InvalidOperationException `
            -Message ($script:localizedData.FailedToSetActivePowerScheme -f $PowerPlanGuid, $_.Exception.NativeErrorCode, $_.Exception.Message)
    }
}

<#
    .SYNOPSIS
        Returns the value of the provided in the Name parameter, at the registry
        location provided in the Path parameter.
 
    .PARAMETER Path
        String containing the path in the registry to the property name.
 
    .PARAMETER PropertyName
        String containing the name of the property for which the value is returned.
#>

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

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

    $getItemPropertyParameters = @{
        Path = $Path
        Name = $Name
    }

    <#
        Using a try/catch block instead of 'SilentlyContinue' to be
        able to unit test a failing registry path.
    #>

    try
    {
        $getItemPropertyResult = (Get-ItemProperty @getItemPropertyParameters -ErrorAction Stop).$Name
    }
    catch
    {
        $getItemPropertyResult = $null
    }

    return $getItemPropertyResult
}

Export-ModuleMember -Function @(
    'Test-Command'
    'Get-TimeZoneId'
    'Test-TimeZoneId'
    'Set-TimeZoneId'
    'Set-TimeZoneUsingDotNet'
    'Get-PowerPlan'
    'Get-ActivePowerPlan'
    'Set-ActivePowerPlan'
    'Get-RegistryPropertyValue'
)