-
Notifications
You must be signed in to change notification settings - Fork 82
/
ComputerManagementDsc.Common.psm1
832 lines (710 loc) · 26.5 KB
/
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
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
# Import the ComputerManagement Resource Helper Module
Import-Module -Name (Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) `
-ChildPath (Join-Path -Path 'ComputerManagementDsc.ResourceHelper' `
-ChildPath 'ComputerManagementDsc.ResourceHelper.psm1'))
# Import Localization Strings
$script:localizedData = Get-LocalizedData `
-ResourceName 'ComputerManagementDsc.Common' `
-ResourcePath $PSScriptRoot
<#
.SYNOPSIS
Removes common parameters from a hashtable
.DESCRIPTION
This function serves the purpose of removing common parameters and option common parameters from a parameter hashtable
.PARAMETER Hashtable
The parameter hashtable that should be pruned
#>
function Remove-CommonParameter
{
[OutputType([System.Collections.Hashtable])]
[cmdletbinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Collections.Hashtable]
$Hashtable
)
$inputClone = $Hashtable.Clone()
$commonParameters = [System.Management.Automation.PSCmdlet]::CommonParameters
$commonParameters += [System.Management.Automation.PSCmdlet]::OptionalCommonParameters
$Hashtable.Keys | Where-Object { $_ -in $commonParameters } | ForEach-Object {
$inputClone.Remove($_)
}
return $inputClone
}
<#
.SYNOPSIS
Tests the status of DSC resource parameters
.DESCRIPTION
This function tests the parameter status of DSC resource parameters against the current values present on the system
.PARAMETER CurrentValues
A hashtable with the current values on the system, obtained by e.g. Get-TargetResource
.PARAMETER DesiredValues
The hashtable of desired values
.PARAMETER ValuesToCheck
The values to check if not all values should be checked
.PARAMETER TurnOffTypeChecking
Indicates that the type of the parameter should not be checked
#>
function Test-DscParameterState
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Collections.Hashtable]
$CurrentValues,
[Parameter(Mandatory = $true)]
[System.Object]
$DesiredValues,
[Parameter()]
[System.String[]]
$ValuesToCheck,
[Parameter()]
[switch]
$TurnOffTypeChecking
)
$returnValue = $true
$types = 'System.Management.Automation.PSBoundParametersDictionary', 'System.Collections.Hashtable', 'Microsoft.Management.Infrastructure.CimInstance'
if ($DesiredValues.GetType().FullName -notin $types)
{
New-InvalidArgumentException `
-Message ($script:localizedData.InvalidDesiredValuesError -f $DesiredValues.GetType().FullName) `
-ArgumentName 'DesiredValues'
}
if ($DesiredValues -is [Microsoft.Management.Infrastructure.CimInstance] -and -not $ValuesToCheck)
{
New-InvalidArgumentException `
-Message $script:localizedData.InvalidValuesToCheckError `
-ArgumentName 'ValuesToCheck'
}
$desiredValuesClean = Remove-CommonParameter -Hashtable $DesiredValues
if (-not $ValuesToCheck)
{
$keyList = $desiredValuesClean.Keys
}
else
{
$keyList = $ValuesToCheck
}
foreach ($key in $keyList)
{
if ($null -ne $desiredValuesClean.$key)
{
$desiredType = $desiredValuesClean.$key.GetType()
}
else
{
$desiredType = [psobject] @{
Name = 'Unknown'
}
}
if ($null -ne $CurrentValues.$key)
{
$currentType = $CurrentValues.$key.GetType()
}
else
{
$currentType = [psobject] @{
Name = 'Unknown'
}
}
if ($currentType.Name -ne 'Unknown' -and $desiredType.Name -eq 'PSCredential')
{
# This is a credential object. Compare only the user name
if ($currentType.Name -eq 'PSCredential' -and $CurrentValues.$key.UserName -eq $desiredValuesClean.$key.UserName)
{
Write-Verbose -Message ($script:localizedData.MatchPsCredentialUsernameMessage -f $CurrentValues.$key.UserName, $desiredValuesClean.$key.UserName)
continue
}
else
{
Write-Verbose -Message ($script:localizedData.NoMatchPsCredentialUsernameMessage -f $CurrentValues.$key.UserName, $desiredValuesClean.$key.UserName)
$returnValue = $false
}
# Assume the string is our username when the matching desired value is actually a credential
if ($currentType.Name -eq 'string' -and $CurrentValues.$key -eq $desiredValuesClean.$key.UserName)
{
Write-Verbose -Message ($script:localizedData.MatchPsCredentialUsernameMessage -f $CurrentValues.$key, $desiredValuesClean.$key.UserName)
continue
}
else
{
Write-Verbose -Message ($script:localizedData.NoMatchPsCredentialUsernameMessage -f $CurrentValues.$key, $desiredValuesClean.$key.UserName)
$returnValue = $false
}
}
if (-not $TurnOffTypeChecking)
{
if (($desiredType.Name -ne 'Unknown' -and $currentType.Name -ne 'Unknown') -and
$desiredType.FullName -ne $currentType.FullName)
{
Write-Verbose -Message ($script:localizedData.NoMatchTypeMismatchMessage -f $key, $currentType.Name, $desiredType.Name)
continue
}
}
if ($CurrentValues.$key -eq $desiredValuesClean.$key -and -not $desiredType.IsArray)
{
Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key)
continue
}
if ($desiredValuesClean.GetType().Name -in 'HashTable', 'PSBoundParametersDictionary')
{
$checkDesiredValue = $desiredValuesClean.ContainsKey($key)
}
else
{
$checkDesiredValue = Test-DscObjectHasProperty -Object $desiredValuesClean -PropertyName $key
}
if (-not $checkDesiredValue)
{
Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key)
continue
}
if ($desiredType.IsArray)
{
Write-Verbose -Message ($script:localizedData.TestDscParameterCompareMessage -f $key)
if (-not $CurrentValues.ContainsKey($key) -or -not $CurrentValues.$key)
{
Write-Verbose -Message ($script:localizedData.NoMatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key)
$returnValue = $false
continue
}
elseif ($CurrentValues.$key.Count -ne $DesiredValues.$key.Count)
{
Write-Verbose -Message ($script:localizedData.NoMatchValueDifferentCountMessage -f $desiredType.Name, $key, $CurrentValues.$key.Count, $desiredValuesClean.$key.Count)
$returnValue = $false
continue
}
else
{
$desiredArrayValues = $DesiredValues.$key
$currentArrayValues = $CurrentValues.$key
for ($i = 0; $i -lt $desiredArrayValues.Count; $i++)
{
if ($null -ne $desiredArrayValues[$i])
{
$desiredType = $desiredArrayValues[$i].GetType()
}
else
{
$desiredType = [psobject]@{
Name = 'Unknown'
}
}
if ($null -ne $currentArrayValues[$i])
{
$currentType = $currentArrayValues[$i].GetType()
}
else
{
$currentType = [psobject]@{
Name = 'Unknown'
}
}
if (-not $TurnOffTypeChecking)
{
if (($desiredType.Name -ne 'Unknown' -and $currentType.Name -ne 'Unknown') -and
$desiredType.FullName -ne $currentType.FullName)
{
Write-Verbose -Message ($script:localizedData.NoMatchElementTypeMismatchMessage -f $key, $i, $currentType.Name, $desiredType.Name)
$returnValue = $false
continue
}
}
if ($desiredArrayValues[$i] -ne $currentArrayValues[$i])
{
Write-Verbose -Message ($script:localizedData.NoMatchElementValueMismatchMessage -f $i, $desiredType.Name, $key, $currentArrayValues[$i], $desiredArrayValues[$i])
$returnValue = $false
continue
}
else
{
Write-Verbose -Message ($script:localizedData.MatchElementValueMessage -f $i, $desiredType.Name, $key, $currentArrayValues[$i], $desiredArrayValues[$i])
continue
}
}
}
}
else
{
if ($desiredValuesClean.$key -ne $CurrentValues.$key)
{
Write-Verbose -Message ($script:localizedData.NoMatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key)
$returnValue = $false
}
}
}
Write-Verbose -Message ($script:localizedData.TestDscParameterResultMessage -f $returnValue)
return $returnValue
}
<#
.SYNOPSIS
Tests of an object has a property
.PARAMETER Object
The object to test
.PARAMETER PropertyName
The property name
#>
function Test-DscObjectHasProperty
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
[Parameter(Mandatory = $true)]
[System.Object]
$Object,
[Parameter(Mandatory = $true)]
[System.String]
$PropertyName
)
if ($Object.PSObject.Properties.Name -contains $PropertyName)
{
return [System.Boolean] $Object.$PropertyName
}
return $false
}
<#
.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 ($LocalizedData.GettingTimeZoneMessage -f 'Cmdlets')
$timeZone = (Get-TimeZone).StandardName
}
else
{
Write-Verbose -Message ($LocalizedData.GettingTimeZoneMessage -f 'CIM')
$timeZone = (Get-CimInstance `
-ClassName Win32_TimeZone `
-Namespace root\cimv2).StandardName
}
Write-Verbose -Message ($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 ($LocalizedData.SettingTimeZoneMessage -f $TimeZoneId, '.NET')
Set-TimeZoneUsingDotNet -TimeZoneId $TimeZoneId
}
else
{
# For anything else use TZUTIL.EXE.
Write-Verbose -Message ($LocalizedData.SettingTimeZoneMessage -f $TimeZoneId, 'TZUTIL.EXE')
try
{
& tzutil.exe @('/s', $TimeZoneId)
}
catch
{
Write-Verbose -Message $_.Exception.Message
} # try
} # if
} # if
Write-Verbose -Message ($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 ($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 all available power plans/schemes or a specific power plan
The function returns an array with one or more hashtable(s) containing
the friendly name and GUID of the power plan(s).
.PARAMETER PowerPlanFriendlyName
Friendly name or GUID of a power plan to get.
When not specified the function will return all available power plans.
.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 PowerPlan resource.
#>
function Get-PowerPlan {
[CmdletBinding()]
param
(
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[System.String]
$PowerPlan
)
$ErrorActionPreference = 'Stop'
# 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
$guids = @()
# 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 -eq 0)
{
try {
# Allocate buffer
$readBuffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([int]$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)
# Create a managed Guid object form the unmanaged memory block
$planGuid = [System.Runtime.InteropServices.Marshal]::PtrToStructure($readBuffer, [System.Type][guid])
# ReturnCode 259 from the native function means no more data
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([int]$returnCode))
New-InvalidOperationException `
-Message ($script:localizedData.UnableToEnumeratingPowerSchemes -f $win32Exception.NativeErrorCode, $win32Exception.Message)
}
$guids += $planGuid
}
finally {
# Free up memory
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($readBuffer)
}
$index++
}
# Now get the friendly name for each power plan so we can filter on name if needed.
$allAvailablePowerPlans = @()
foreach($planGuid in $guids)
{
$planFriendlyName = Get-PowerPlanFriendlyName -PowerPlanGuid $planGuid
$availablePowerPlan = @{
FriendlyName = $planFriendlyName
Guid = $planGuid
}
$allAvailablePowerPlans += $availablePowerPlan
}
# If a specific power plan is specified filter for it.
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 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.
#>
function Get-PowerPlanFriendlyName
{
[CmdletBinding()]
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([int]$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 unmanned memory block.
$friendlyName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptrName)
return $friendlyName
}
else
{
throw [ComponentModel.Win32Exception]::new([int]$returnCode)
}
}
finally
{
# Make sure allocated memory is freed up again.
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptrName)
}
}
else
{
throw [ComponentModel.Win32Exception]::new([int]$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 on some platforms issues 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()]
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([int]$returnCode))
New-InvalidOperationException `
-Message ($script:localizedData.FailedToGetActivePowerScheme -f $win32Exception.NativeErrorCode, $win32Exception.Message)
}
# Create a managed Guid object form the unmanaged memory block and return it
return [System.Runtime.InteropServices.Marshal]::PtrToStructure($activeSchemeGuid, [System.Type][guid])
}
finally
{
# Make sure allocated memory is freed up again.
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($activeSchemeGuid)
}
}
<#
.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 PowerPlan resource.
#>
function Set-ActivePowerPlan {
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Guid]
$PowerPlanGuid
)
# Set to stop so that the errors from powercfg.exe are terminating
$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)
}
}
Export-ModuleMember -Function `
Test-DscParameterState, `
Test-DscObjectHasProperty, `
Test-Command, `
Get-TimeZoneId, `
Test-TimeZoneId, `
Set-TimeZoneId, `
Set-TimeZoneUsingDotNet, `
Get-PowerPlan, `
Get-ActivePowerPlan, `
Set-ActivePowerPlan