-
Notifications
You must be signed in to change notification settings - Fork 22
/
Invoke-CMDownloadBIOSPackage.ps1
1322 lines (1136 loc) · 66.7 KB
/
Invoke-CMDownloadBIOSPackage.ps1
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
<#
.SYNOPSIS
Download BIOS package (regular package) matching computer model and manufacturer.
.DESCRIPTION
This script will determine the model of the computer and manufacturer and then query the specified endpoint
for ConfigMgr WebService for a list of Packages. It then sets the OSDDownloadDownloadPackages variable to include
the PackageID property of a package matching the computer model. If multiple packages are detect, it will select
most current one by the creation date of the packages.
.PARAMETER BareMetal
Set the script to operate in 'BareMetal' (WinPE) deployment type mode.
.PARAMETER BIOSUpdate
Set the script to operate in 'BIOSUpdate' (full OS) deployment type mode.
.PARAMETER DebugMode
Set the script to operate in 'DebugMode' deployment type mode.
.PARAMETER Endpoint
Specify the internal fully qualified domain name of the server hosting the AdminService, e.g. CM01.domain.local.
.PARAMETER UserName
Specify the service account user name used for authenticating against the AdminService endpoint.
.PARAMETER Password
Specify the service account password used for authenticating against the AdminService endpoint.
.PARAMETER Filter
Define a filter used when calling ConfigMgr WebService to only return objects matching the filter.
.PARAMETER OperationalMode
Define the operational mode, either Production or Pilot, for when calling ConfigMgr WebService to only return objects matching the selected operational mode.
.PARAMETER Manufacturer
Override the automatically detected computer manufacturer when running in debug mode.
.PARAMETER ComputerModel
Override the automatically detected computer model when running in debug mode.
.PARAMETER SystemSKU
Override the automatically detected SystemSKU when running in debug mode.
.PARAMETER OSVersionFallback
Use this switch to check for drivers packages that matches earlier versions of Windows than what's specified as input for TargetOSVersion.
.EXAMPLE
# Detect and download latest available BIOS package with ConfigMgr through the admin service in a baremetal deployment (default):
.\Invoke-CMDownloadBIOSPackage.ps1 -BareMetal -Endpoint "CM01.domain.com"
# Detect and download latest available BIOS package with ConfigMgr through the admin service in a full OS deployment:
.\Invoke-CMDownloadBIOSPackage.ps1 -BIOSUpdate -Endpoint "CM01.domain.com"
# Detect, and report on the matched BIOS release without downloading / in full OS
.\Invoke-CMDownloadBIOSPackage.ps1 -Endpoint "CM01.domain.com" -UserName "Username" -Password "Password" -DebugMode
# Detect, and report on the matched BIOS release without downloading / in full OS, with the make / model / sku specified
.\Invoke-CMDownloadBIOSPackage.ps1 -Endpoint "CM01.domain.com" -UserName "Username" -Password "Password" -Manufacturer "HP" -ComptuerModel "ZBook Studio x360 G5" -SystemSKU "8427" -DebugMode
.NOTES
FileName: Invoke-CMDownloadBIOSPackage.ps1
Author: Nickolaj Andersen / Maurice Daly
Contact: @NickolajA / @MoDaly_IT
Created: 2020-10-30
Updated: 2020-10-30
Version history:
3.0.0 - (2020-10-30) - Script created
3.0.1 - (2020-12-04) - Fixes to parameter sets, matching logic and removal of no longer code
- Added TS variable support for Resource URL
3.0.2 - (2020-12-09) - Added new functionality to be able to read a custom Application ID URI, if the default of https://ConfigMgrService is not defined on the ServerApp.
3.0.3 - (2020-12-10) - Fixed issue in WinPE, with addition of baremetal parameter switch (now default)
Added BIOSUpdate parameter switch for Full OS deployments
#>
[CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = "BareMetal")]
param (
[parameter(Mandatory = $true, ParameterSetName = "BareMetal", HelpMessage = "Set the script to operate in 'BareMetal' deployment type mode.")]
[switch]$BareMetal,
[parameter(Mandatory = $true, ParameterSetName = "BIOSUpdate", HelpMessage = "Set the script to operate in 'BIOSUpdate' deployment type mode.")]
[switch]$BIOSUpdate,
[parameter(Mandatory = $true, ParameterSetName = "BIOSUpdate", HelpMessage = "Specify the internal fully qualified domain name of the server hosting the AdminService, e.g. CM01.domain.local.")]
[parameter(Mandatory = $true, ParameterSetName = "BareMetal")]
[parameter(Mandatory = $true, ParameterSetName = "Debug")]
[ValidateNotNullOrEmpty()]
[string]$Endpoint,
[parameter(Mandatory = $false, ParameterSetName = "Debug", HelpMessage = "Set the script to operate in 'DebugMode' deployment type mode.")]
[switch]$DebugMode,
[parameter(Mandatory = $true, ParameterSetName = "Debug", HelpMessage = "Specify the service account user name used for authenticating against the AdminService endpoint.")]
[ValidateNotNullOrEmpty()]
[string]$UserName = "",
[parameter(Mandatory = $true, ParameterSetName = "Debug", HelpMessage = "Specify the service account password used for authenticating against the AdminService endpoint.")]
[ValidateNotNullOrEmpty()]
[string]$Password = "",
[parameter(Mandatory = $false, ParameterSetName = "BIOSUpdate", HelpMessage = "Define a filter used when calling the AdminService to only return objects matching the filter.")]
[parameter(Mandatory = $false, ParameterSetName = "BareMetal")]
[ValidateNotNullOrEmpty()]
[string]$Filter = "BIOS",
[parameter(Mandatory = $false, ParameterSetName = "BIOSUpdate", HelpMessage = "Define the operational mode, either Production or Pilot, for when calling ConfigMgr WebService to only return objects matching the selected operational mode.")]
[parameter(Mandatory = $false, ParameterSetName = "BareMetal")]
[parameter(Mandatory = $true, ParameterSetName = "Debug")]
[ValidateNotNullOrEmpty()]
[ValidateSet("Production", "Pilot")]
[string]$OperationalMode = "Production",
[parameter(Mandatory = $false, ParameterSetName = "Debug", HelpMessage = "Override the automatically detected computer manufacturer when running in debug mode.")]
[ValidateNotNullOrEmpty()]
[ValidateSet("Hewlett-Packard", "HP", "Dell", "Lenovo", "Microsoft", "Fujitsu", "Panasonic", "Viglen", "AZW")]
[string]$Manufacturer,
[parameter(Mandatory = $false, ParameterSetName = "Debug", HelpMessage = "Override the automatically detected computer model when running in debug mode.")]
[ValidateNotNullOrEmpty()]
[string]$ComputerModel,
[parameter(Mandatory = $false, ParameterSetName = "Debug", HelpMessage = "Override the automatically detected SystemSKU when running in debug mode.")]
[ValidateNotNullOrEmpty()]
[string]$SystemSKU
)
Begin {
# Load Microsoft.SMS.TSEnvironment COM object
if ($PSCmdLet.ParameterSetName -notlike "Debug") {
try {
$TSEnvironment = New-Object -ComObject "Microsoft.SMS.TSEnvironment" -ErrorAction Stop
} catch [System.Exception] {
Write-Warning -Message "Unable to construct Microsoft.SMS.TSEnvironment object"; exit
}
}
# Set Security Protocol (TLS)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}
Process {
# Set Log Path
switch ($PSCmdLet.ParameterSetName) {
"Debug" {
$LogsDirectory = Join-Path -Path $env:SystemRoot -ChildPath "Temp"
}
default {
$LogsDirectory = $Script:TSEnvironment.Value("_SMSTSLogPath")
}
}
# Functions
function Write-CMLogEntry {
param (
[parameter(Mandatory = $true, HelpMessage = "Value added to the log file.")]
[ValidateNotNullOrEmpty()]
[string]$Value,
[parameter(Mandatory = $true, HelpMessage = "Severity for the log entry. 1 for Informational, 2 for Warning and 3 for Error.")]
[ValidateNotNullOrEmpty()]
[ValidateSet("1", "2", "3")]
[string]$Severity,
[parameter(Mandatory = $false, HelpMessage = "Name of the log file that the entry will written to.")]
[ValidateNotNullOrEmpty()]
[string]$FileName = "ApplyBIOSPackage.log"
)
# Determine log file location
$LogFilePath = Join-Path -Path $LogsDirectory -ChildPath $FileName
# Construct time stamp for log entry
if (-not (Test-Path -Path 'variable:global:TimezoneBias')) {
[string]$global:TimezoneBias = [System.TimeZoneInfo]::Local.GetUtcOffset((Get-Date)).TotalMinutes
if ($TimezoneBias -match "^-") {
$TimezoneBias = $TimezoneBias.Replace('-', '+')
} else {
$TimezoneBias = '-' + $TimezoneBias
}
}
$Time = -join @((Get-Date -Format "HH:mm:ss.fff"), $TimezoneBias)
# Construct date for log entry
$Date = (Get-Date -Format "MM-dd-yyyy")
# Construct context for log entry
$Context = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
# Construct final log entry
$LogText = "<![LOG[$($Value)]LOG]!><time=""$($Time)"" date=""$($Date)"" component=""ApplyBIOSPackage"" context=""$($Context)"" type=""$($Severity)"" thread=""$($PID)"" file="""">"
# Add value to log file
try {
Out-File -InputObject $LogText -Append -NoClobber -Encoding Default -FilePath $LogFilePath -ErrorAction Stop
} catch [System.Exception] {
Write-Warning -Message "Unable to append log entry to ApplyBIOSPackage.log file. Error message at line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
}
}
function Invoke-Executable {
param (
[parameter(Mandatory = $true, HelpMessage = "Specify the file name or path of the executable to be invoked, including the extension")]
[ValidateNotNullOrEmpty()]
[string]$FilePath,
[parameter(Mandatory = $false, HelpMessage = "Specify arguments that will be passed to the executable")]
[ValidateNotNull()]
[string]$Arguments
)
# Construct a hash-table for default parameter splatting
$SplatArgs = @{
FilePath = $FilePath
NoNewWindow = $true
Passthru = $true
ErrorAction = "Stop"
}
# Add ArgumentList param if present
if (-not ([System.String]::IsNullOrEmpty($Arguments))) {
$SplatArgs.Add("ArgumentList", $Arguments)
}
# Invoke executable and wait for process to exit
try {
$Invocation = Start-Process @SplatArgs
$Handle = $Invocation.Handle
$Invocation.WaitForExit()
} catch [System.Exception] {
Write-Warning -Message $_.Exception.Message; break
}
return $Invocation.ExitCode
}
function Invoke-CMDownloadContent {
param (
[parameter(Mandatory = $true, ParameterSetName = "NoPath", HelpMessage = "Specify a PackageID that will be downloaded.")]
[Parameter(ParameterSetName = "CustomPath")]
[ValidateNotNullOrEmpty()]
[ValidatePattern("^[A-Z0-9]{3}[A-F0-9]{5}$")]
[string]$PackageID,
[parameter(Mandatory = $true, ParameterSetName = "NoPath", HelpMessage = "Specify the download location type.")]
[Parameter(ParameterSetName = "CustomPath")]
[ValidateNotNullOrEmpty()]
[ValidateSet("Custom", "TSCache", "CCMCache")]
[string]$DestinationLocationType,
[parameter(Mandatory = $true, ParameterSetName = "NoPath", HelpMessage = "Save the download location to the specified variable name.")]
[Parameter(ParameterSetName = "CustomPath")]
[ValidateNotNullOrEmpty()]
[string]$DestinationVariableName,
[parameter(Mandatory = $true, ParameterSetName = "CustomPath", HelpMessage = "When location type is specified as Custom, specify the custom path.")]
[ValidateNotNullOrEmpty()]
[string]$CustomLocationPath
)
# Set OSDDownloadDownloadPackages
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDownloadPackages to: $($PackageID)" -Severity 1
$TSEnvironment.Value("OSDDownloadDownloadPackages") = "$($PackageID)"
# Set OSDDownloadDestinationLocationType
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDestinationLocationType to: $($DestinationLocationType)" -Severity 1
$TSEnvironment.Value("OSDDownloadDestinationLocationType") = "$($DestinationLocationType)"
# Set OSDDownloadDestinationVariable
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDestinationVariable to: $($DestinationVariableName)" -Severity 1
$TSEnvironment.Value("OSDDownloadDestinationVariable") = "$($DestinationVariableName)"
# Set OSDDownloadDestinationPath
if ($DestinationLocationType -like "Custom") {
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDestinationPath to: $($CustomLocationPath)" -Severity 1
$TSEnvironment.Value("OSDDownloadDestinationPath") = "$($CustomLocationPath)"
}
# Set SMSTSDownloadRetryCount to 1000 to overcome potential BranchCache issue that will cause 'SendWinHttpRequest failed. 80072efe'
$TSEnvironment.Value("SMSTSDownloadRetryCount") = 1000
# Invoke download of package content
try {
if ($TSEnvironment.Value("_SMSTSInWinPE") -eq $false) {
Write-CMLogEntry -Value " - Starting package content download process (FullOS), this might take some time" -Severity 1
$ReturnCode = Invoke-Executable -FilePath (Join-Path -Path $env:windir -ChildPath "CCM\OSDDownloadContent.exe")
} else {
Write-CMLogEntry -Value " - Starting package content download process (WinPE), this might take some time" -Severity 1
$ReturnCode = Invoke-Executable -FilePath "OSDDownloadContent.exe"
}
# Reset SMSTSDownloadRetryCount to 5 after attempted download
$TSEnvironment.Value("SMSTSDownloadRetryCount") = 5
# Match on return code
if ($ReturnCode -eq 0) {
Write-CMLogEntry -Value " - Successfully downloaded package content with PackageID: $($PackageID)" -Severity 1
} else {
Write-CMLogEntry -Value " - Failed to download package content with PackageID '$($PackageID)'. Return code was: $($ReturnCode)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
} catch [System.Exception] {
Write-CMLogEntry -Value " - An error occurred while attempting to download package content. Error message: $($_.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
return $ReturnCode
}
function Invoke-CMResetDownloadContentVariables {
# Set OSDDownloadDownloadPackages
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDownloadPackages to a blank value" -Severity 1
$TSEnvironment.Value("OSDDownloadDownloadPackages") = [System.String]::Empty
# Set OSDDownloadDestinationLocationType
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDestinationLocationType to a blank value" -Severity 1
$TSEnvironment.Value("OSDDownloadDestinationLocationType") = [System.String]::Empty
# Set OSDDownloadDestinationVariable
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDestinationVariable to a blank value" -Severity 1
$TSEnvironment.Value("OSDDownloadDestinationVariable") = [System.String]::Empty
# Set OSDDownloadDestinationPath
Write-CMLogEntry -Value " - Setting task sequence variable OSDDownloadDestinationPath to a blank value" -Severity 1
$TSEnvironment.Value("OSDDownloadDestinationPath") = [System.String]::Empty
}
function New-TerminatingErrorRecord {
param (
[parameter(Mandatory = $true, HelpMessage = "Specify the exception message details.")]
[ValidateNotNullOrEmpty()]
[string]$Message,
[parameter(Mandatory = $false, HelpMessage = "Specify the violation exception causing the error.")]
[ValidateNotNullOrEmpty()]
[string]$Exception = "System.Management.Automation.RuntimeException",
[parameter(Mandatory = $false, HelpMessage = "Specify the error category of the exception causing the error.")]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.ErrorCategory]$ErrorCategory = [System.Management.Automation.ErrorCategory]::NotImplemented,
[parameter(Mandatory = $false, HelpMessage = "Specify the target object causing the error.")]
[ValidateNotNullOrEmpty()]
[string]$TargetObject = ([string]::Empty)
)
# Construct new error record to be returned from function based on parameter inputs
$SystemException = New-Object -TypeName $Exception -ArgumentList $Message
$ErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList @($SystemException, $ErrorID, $ErrorCategory, $TargetObject)
# Handle return value
return $ErrorRecord
}
function Get-DeploymentType {
switch ($PSCmdlet.ParameterSetName) {
"XMLPackage" {
# Set required variables for XMLPackage parameter set
$Script:DeploymentMode = $Script:XMLDeploymentType
$Script:PackageSource = "XML Package Logic file"
# Define the path for the pre-downloaded XML Package Logic file called DriverPackages.xml
$script:XMLPackageLogicFile = (Join-Path -Path $TSEnvironment.Value("MDMXMLPackage01") -ChildPath "DriverPackages.xml")
if (-not (Test-Path -Path $XMLPackageLogicFile)) {
Write-CMLogEntry -Value " - Failed to locate required 'DriverPackages.xml' logic file for XMLPackage deployment type, ensure it has been pre-downloaded in a Download Package Content step before running this script" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
default {
$Script:DeploymentMode = $Script:PSCmdlet.ParameterSetName
$Script:PackageSource = "AdminService"
}
}
}
function ConvertTo-ObfuscatedUserName {
param (
[parameter(Mandatory = $true, HelpMessage = "Specify the user name string to be obfuscated for log output.")]
[ValidateNotNullOrEmpty()]
[string]$InputObject
)
# Convert input object to a character array
$UserNameArray = $InputObject.ToCharArray()
# Loop through each character obfuscate every second item, with exceptions of the @ character if present
for ($i = 0; $i -lt $UserNameArray.Count; $i++) {
if ($UserNameArray[$i] -notmatch "@") {
if ($i % 2) {
$UserNameArray[$i] = "*"
}
}
}
# Join character array and return value
return -join @($UserNameArray)
}
function Test-AdminServiceData {
# Validate correct value have been either set as a TS environment variable or passed as parameter input for service account user name used to authenticate against the AdminService
if ([string]::IsNullOrEmpty($Script:UserName)) {
switch ($PSCmdLet.ParameterSetName) {
"Debug" {
Write-CMLogEntry -Value " - Required service account user name could not be determined from parameter input" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
default {
# Attempt to read TSEnvironment variable MDMUserName
$Script:UserName = $TSEnvironment.Value("MDMUserName")
if (-not ([string]::IsNullOrEmpty($Script:UserName))) {
# Obfuscate user name
$ObfuscatedUserName = ConvertTo-ObfuscatedUserName -InputObject $Script:UserName
Write-CMLogEntry -Value " - Successfully read service account user name from TS environment variable 'MDMUserName': $($ObfuscatedUserName)" -Severity 1
} else {
Write-CMLogEntry -Value " - Required service account user name could not be determined from TS environment variable" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
}
} else {
# Obfuscate user name
$ObfuscatedUserName = ConvertTo-ObfuscatedUserName -InputObject $Script:UserName
Write-CMLogEntry -Value " - Successfully read service account user name from parameter input: $($ObfuscatedUserName)" -Severity 1
}
# Validate correct value have been either set as a TS environment variable or passed as parameter input for service account password used to authenticate against the AdminService
if ([string]::IsNullOrEmpty($Script:Password)) {
switch ($Script:PSCmdLet.ParameterSetName) {
"Debug" {
Write-CMLogEntry -Value " - Required service account password could not be determined from parameter input" -Severity 3
}
default {
# Attempt to read TSEnvironment variable MDMPassword
$Script:Password = $TSEnvironment.Value("MDMPassword")
if (-not ([string]::IsNullOrEmpty($Script:Password))) {
Write-CMLogEntry -Value " - Successfully read service account password from TS environment variable 'MDMPassword': ********" -Severity 1
} else {
Write-CMLogEntry -Value " - Required service account password could not be determined from TS environment variable" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
}
} else {
Write-CMLogEntry -Value " - Successfully read service account password from parameter input: ********" -Severity 1
}
# Validate that if determined AdminService endpoint type is external, that additional required TS environment variables are available
if ($Script:AdminServiceEndpointType -like "External") {
if ($Script:PSCmdLet.ParameterSetName -notlike "Debug") {
# Attempt to read TSEnvironment variable MDMExternalEndpoint
$Script:ExternalEndpoint = $TSEnvironment.Value("MDMExternalEndpoint")
if (-not ([string]::IsNullOrEmpty($Script:ExternalEndpoint))) {
Write-CMLogEntry -Value " - Successfully read external endpoint address for AdminService through CMG from TS environment variable 'MDMExternalEndpoint': $($Script:ExternalEndpoint)" -Severity 1
} else {
Write-CMLogEntry -Value " - Required external endpoint address for AdminService through CMG could not be determined from TS environment variable" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
# Attempt to read TSEnvironment variable MDMClientID
$Script:ClientID = $TSEnvironment.Value("MDMClientID")
if (-not ([string]::IsNullOrEmpty($Script:ClientID))) {
Write-CMLogEntry -Value " - Successfully read client identification for AdminService through CMG from TS environment variable 'MDMClientID': $($Script:ClientID)" -Severity 1
} else {
Write-CMLogEntry -Value " - Required client identification for AdminService through CMG could not be determined from TS environment variable" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
# Attempt to read TSEnvironment variable MDMTenantName
$Script:TenantName = $TSEnvironment.Value("MDMTenantName")
if (-not ([string]::IsNullOrEmpty($Script:TenantName))) {
Write-CMLogEntry -Value " - Successfully read client identification for AdminService through CMG from TS environment variable 'MDMTenantName': $($Script:TenantName)" -Severity 1
} else {
Write-CMLogEntry -Value " - Required client identification for AdminService through CMG could not be determined from TS environment variable" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
# Attempt to read TSEnvironment variable MDMApplicationIDURI
$Script:ApplicationIDURI = $TSEnvironment.Value("MDMApplicationIDURI")
if (-not ([string]::IsNullOrEmpty($Script:ApplicationIDURI))) {
Write-CMLogEntry -Value " - Successfully read Application ID URI from TS environment variable 'MDMApplicationIDURI': $($Script:ApplicationIDURI)" -Severity 1
} else {
Write-CMLogEntry -Value " - Using standard Application ID URI value: https://ConfigMgrService" -Severity 2
$Script:ApplicationIDURI = "https://ConfigMgrService"
}
}
}
}
function Get-AdminServiceEndpointType {
switch ($Script:DeploymentMode) {
"BareMetal" {
$SMSInWinPE = $TSEnvironment.Value("_SMSTSInWinPE")
if ($SMSInWinPE -eq $true) {
Write-CMLogEntry -Value " - Detected that script was running within a task sequence in WinPE phase, automatically configuring AdminService endpoint type" -Severity 1
$Script:AdminServiceEndpointType = "Internal"
} else {
Write-CMLogEntry -Value " - Detected that script was not running in WinPE of a bare metal deployment type, this is not a supported scenario" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
"Debug" {
$Script:AdminServiceEndpointType = "Internal"
}
default {
Write-CMLogEntry -Value " - Attempting to determine AdminService endpoint type based on current active Management Point candidates and from ClientInfo class" -Severity 1
# Determine active MP candidates and if
$ActiveMPCandidates = Get-WmiObject -Namespace "root\ccm\LocationServices" -Class "SMS_ActiveMPCandidate"
$ActiveMPInternalCandidatesCount = ($ActiveMPCandidates | Where-Object {
$PSItem.Type -like "Assigned"
} | Measure-Object).Count
$ActiveMPExternalCandidatesCount = ($ActiveMPCandidates | Where-Object {
$PSItem.Type -like "Internet"
} | Measure-Object).Count
# Determine if ConfigMgr client has detected if the computer is currently on internet or intranet
$CMClientInfo = Get-WmiObject -Namespace "root\ccm" -Class "ClientInfo"
switch ($CMClientInfo.InInternet) {
$true {
if ($ActiveMPExternalCandidatesCount -ge 1) {
$Script:AdminServiceEndpointType = "External"
} else {
Write-CMLogEntry -Value " - Detected as an Internet client but unable to determine External AdminService endpoint, bailing out" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
$false {
if ($ActiveMPInternalCandidatesCount -ge 1) {
$Script:AdminServiceEndpointType = "Internal"
} else {
Write-CMLogEntry -Value " - Detected as an Intranet client but unable to determine Internal AdminService endpoint, bailing out" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
}
}
}
Write-CMLogEntry -Value " - Determined AdminService endpoint type as: $($AdminServiceEndpointType)" -Severity 1
}
function Set-AdminServiceEndpointURL {
switch ($Script:AdminServiceEndpointType) {
"Internal" {
$Script:AdminServiceURL = "https://{0}/AdminService/wmi" -f $Endpoint
}
"External" {
$Script:AdminServiceURL = "{0}/wmi" -f $ExternalEndpoint
}
}
Write-CMLogEntry -Value " - Setting 'AdminServiceURL' variable to: $($Script:AdminServiceURL)" -Severity 1
}
function Install-AuthModule {
# Determine if the PSIntuneAuth module needs to be installed
try {
Write-CMLogEntry -Value " - Attempting to locate PSIntuneAuth module" -Severity 1
$PSIntuneAuthModule = Get-InstalledModule -Name "PSIntuneAuth" -ErrorAction Stop -Verbose:$false
if ($PSIntuneAuthModule -ne $null) {
Write-CMLogEntry -Value " - Authentication module detected, checking for latest version" -Severity 1
$LatestModuleVersion = (Find-Module -Name "PSIntuneAuth" -ErrorAction SilentlyContinue -Verbose:$false).Version
if ($LatestModuleVersion -gt $PSIntuneAuthModule.Version) {
Write-CMLogEntry -Value " - Latest version of PSIntuneAuth module is not installed, attempting to install: $($LatestModuleVersion.ToString())" -Severity 1
$UpdateModuleInvocation = Update-Module -Name "PSIntuneAuth" -Scope CurrentUser -Force -ErrorAction Stop -Confirm:$false -Verbose:$false
}
}
} catch [System.Exception] {
Write-CMLogEntry -Value " - Unable to detect PSIntuneAuth module, attempting to install from PSGallery" -Severity 2
try {
# Install NuGet package provider
$PackageProvider = Install-PackageProvider -Name "NuGet" -Force -Verbose:$false
# Install PSIntuneAuth module
Install-Module -Name "PSIntuneAuth" -Scope AllUsers -Force -ErrorAction Stop -Confirm:$false -Verbose:$false
Write-CMLogEntry -Value " - Successfully installed PSIntuneAuth module" -Severity 1
} catch [System.Exception] {
Write-CMLogEntry -Value " - An error occurred while attempting to install PSIntuneAuth module. Error message: $($_.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
}
function Get-AuthToken {
try {
# Attempt to install PSIntuneAuth module, if already installed ensure the latest version is being used
Install-AuthModule
# Import MS Intune Auth Token
Write-CMLogEntry -Value " - Importing PSIntuneAuth PS module" -Severity 1
Import-Module -Name PSIntuneAuth
# Retrieve authentication token
Write-CMLogEntry -Value " - Attempting to retrieve authentication token using native client with ID: $($ClientID)" -Severity 1
$Script:AuthToken = Get-MSIntuneAuthToken -TenantName $TenantName -ClientID $ClientID -Credential $Credential -Resource $ApplicationIDURI -RedirectUri "https://login.microsoftonline.com/common/oauth2/nativeclient" -ErrorAction Stop
Write-CMLogEntry -Value " - Successfully retrieved authentication token" -Severity 1
} catch [System.Exception] {
Write-CMLogEntry -Value " - Failed to retrieve authentication token. Error message: $($PSItem.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
function Get-AuthCredential {
# Construct PSCredential object for authentication
$EncryptedPassword = ConvertTo-SecureString -String $Script:Password -AsPlainText -Force
$Script:Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList @($Script:UserName, $EncryptedPassword)
}
function Get-AdminServiceItem {
param (
[parameter(Mandatory = $true, HelpMessage = "Specify the resource for the AdminService API call, e.g. '/SMS_Package'.")]
[ValidateNotNullOrEmpty()]
[string]$Resource
)
# Construct array object to hold return value
$PackageArray = New-Object -TypeName System.Collections.ArrayList
switch ($Script:AdminServiceEndpointType) {
"External" {
try {
$AdminServiceUri = $AdminServiceURL + $Resource
Write-CMLogEntry -Value " - Calling AdminService endpoint with URI: $($AdminServiceUri)" -Severity 1
$AdminServiceResponse = Invoke-RestMethod -Method Get -Uri $AdminServiceUri -Headers $AuthToken -ErrorAction Stop
} catch [System.Exception] {
Write-CMLogEntry -Value " - Failed to retrieve available package items from AdminService endpoint. Error message: $($PSItem.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
"Internal" {
$AdminServiceUri = $AdminServiceURL + $Resource
Write-CMLogEntry -Value " - Calling AdminService endpoint with URI: $($AdminServiceUri)" -Severity 1
try {
# Call AdminService endpoint to retrieve package data
$AdminServiceResponse = Invoke-RestMethod -Method Get -Uri $AdminServiceUri -Credential $Credential -ErrorAction Stop
} catch [System.Security.Authentication.AuthenticationException] {
Write-CMLogEntry -Value " - The remote AdminService endpoint certificate is invalid according to the validation procedure. Error message: $($PSItem.Exception.Message)" -Severity 2
Write-CMLogEntry -Value " - Will attempt to set the current session to ignore self-signed certificates and retry AdminService endpoint connection" -Severity 2
# Attempt to ignore self-signed certificate binding for AdminService
# Convert encoded base64 string for ignore self-signed certificate validation functionality
$CertificationValidationCallbackEncoded = "DQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAdQBzAGkAbgBnACAAUwB5AHMAdABlAG0AOwANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAB1AHMAaQBuAGcAIABTAHkAcwB0AGUAbQAuAE4AZQB0ADsADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAdQBzAGkAbgBnACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAZQBjAHUAcgBpAHQAeQA7AA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAHUAcwBpAG4AZwAgAFMAeQBzAHQAZQBtAC4AUwBlAGMAdQByAGkAdAB5AC4AQwByAHkAcAB0AG8AZwByAGEAcABoAHkALgBYADUAMAA5AEMAZQByAHQAaQBmAGkAYwBhAHQAZQBzADsADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAcAB1AGIAbABpAGMAIABjAGwAYQBzAHMAIABTAGUAcgB2AGUAcgBDAGUAcgB0AGkAZgBpAGMAYQB0AGUAVgBhAGwAaQBkAGEAdABpAG8AbgBDAGEAbABsAGIAYQBjAGsADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAewANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAHAAdQBiAGwAaQBjACAAcwB0AGEAdABpAGMAIAB2AG8AaQBkACAASQBnAG4AbwByAGUAKAApAA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAewANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAaQBmACgAUwBlAHIAdgBpAGMAZQBQAG8AaQBuAHQATQBhAG4AYQBnAGUAcgAuAFMAZQByAHYAZQByAEMAZQByAHQAaQBmAGkAYwBhAHQAZQBWAGEAbABpAGQAYQB0AGkAbwBuAEMAYQBsAGwAYgBhAGMAawAgAD0APQBuAHUAbABsACkADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAHsADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAUwBlAHIAdgBpAGMAZQBQAG8AaQBuAHQATQBhAG4AYQBnAGUAcgAuAFMAZQByAHYAZQByAEMAZQByAHQAaQBmAGkAYwBhAHQAZQBWAGEAbABpAGQAYQB0AGkAbwBuAEMAYQBsAGwAYgBhAGMAawAgACsAPQAgAA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAZABlAGwAZQBnAGEAdABlAA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAKAANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAATwBiAGoAZQBjAHQAIABvAGIAagAsACAADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAFgANQAwADkAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBlAHIAdABpAGYAaQBjAGEAdABlACwAIAANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAWAA1ADAAOQBDAGgAYQBpAG4AIABjAGgAYQBpAG4ALAAgAA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIABTAHMAbABQAG8AbABpAGMAeQBFAHIAcgBvAHIAcwAgAGUAcgByAG8AcgBzAA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAKQANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAHsADQAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAHIAZQB0AHUAcgBuACAAdAByAHUAZQA7AA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAfQA7AA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAB9AA0ACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAfQANAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAB9AA0ACgAgACAAIAAgACAAIAAgACAA"
$CertificationValidationCallback = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($CertificationValidationCallbackEncoded))
# Load required type definition to be able to ignore self-signed certificate to circumvent issues with AdminService running with ConfigMgr self-signed certificate binding
Add-Type -TypeDefinition $CertificationValidationCallback
[ServerCertificateValidationCallback]::Ignore()
try {
# Call AdminService endpoint to retrieve package data
$AdminServiceResponse = Invoke-RestMethod -Method Get -Uri $AdminServiceUri -Credential $Credential -ErrorAction Stop
} catch [System.Exception] {
Write-CMLogEntry -Value " - Failed to retrieve available package items from AdminService endpoint. Error message: $($PSItem.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
} catch {
Write-CMLogEntry -Value " - Failed to retrieve available package items from AdminService endpoint. Error message: $($PSItem.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
}
# Add returned driver package objects to array list
if ($AdminServiceResponse.value -ne $null) {
foreach ($Package in $AdminServiceResponse.value) {
$PackageArray.Add($Package) | Out-Null
}
}
# Handle return value
return $PackageArray
}
function Get-BIOSPackages {
try {
# Retrieve BIOS packages but filter out matches depending on script operational mode
switch ($OperationalMode) {
"Production" {
if ($Script:PSCmdlet.ParameterSetName -like "XMLPackage") {
Write-CMLogEntry -Value " - Reading XML content logic file BIOS package entries" -Severity 1
$Packages = (([xml]$(Get-Content -Path $XMLPackageLogicFile -Raw)).ArrayOfCMPackage).CMPackage | Where-Object {
$_.Name -notmatch "Pilot" -and $_.Name -notmatch "Legacy" -and $_.Name -match $Filter
}
} else {
Write-CMLogEntry -Value " - Querying AdminService for BIOS package instances" -Severity 1
$Packages = Get-AdminServiceItem -Resource "/SMS_Package?`$filter=contains(Name,'$($Filter)')" | Where-Object {
$_.Name -notmatch "Pilot" -and $_.Name -notmatch "Retired"
}
}
}
"Pilot" {
if ($Script:PSCmdlet.ParameterSetName -like "XMLPackage") {
Write-CMLogEntry -Value " - Reading XML content logic file BIOS package entries" -Severity 1
$Packages = (([xml]$(Get-Content -Path $XMLPackageLogicFile -Raw)).ArrayOfCMPackage).CMPackage | Where-Object {
$_.Name -match "Pilot" -and $_.Name -match $Filter
}
} else {
Write-CMLogEntry -Value " - Querying AdminService for BIOS package instances" -Severity 1
$Packages = Get-AdminServiceItem -Resource "/SMS_Package?`$filter=contains(Name,'$($Filter)')" | Where-Object {
$_.Name -match "Pilot"
}
}
}
}
# Handle return value
if ($Packages -ne $null) {
Write-CMLogEntry -Value " - Retrieved a total of '$(($Packages | Measure-Object).Count)' BIOS packages from $($Script:PackageSource) matching operational mode: $($OperationalMode)" -Severity 1
return $Packages
} else {
Write-CMLogEntry -Value " - Retrieved a total of '0' BIOS packages from $($Script:PackageSource) matching operational mode: $($OperationalMode)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
} catch [System.Exception] {
Write-CMLogEntry -Value " - An error occurred while calling $($Script:PackageSource) for a list of available BIOS packages. Error message: $($_.Exception.Message)" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
function Get-ComputerData {
# Create a custom object for computer details gathered from local WMI
$ComputerDetails = [PSCustomObject]@{
Manufacturer = $null
Model = $null
SystemSKU = $null
FallbackSKU = $null
}
# Gather computer details based upon specific computer manufacturer
$ComputerManufacturer = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Manufacturer).Trim()
switch -Wildcard ($ComputerManufacturer) {
"*Microsoft*" {
$ComputerDetails.Manufacturer = "Microsoft"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = Get-WmiObject -Namespace "root\wmi" -Class "MS_SystemInformation" | Select-Object -ExpandProperty SystemSKU
}
"*HP*" {
$ComputerDetails.Manufacturer = "HP"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-CIMInstance -ClassName "MS_SystemInformation" -NameSpace "root\WMI").BaseBoardProduct.Trim()
}
"*Hewlett-Packard*" {
$ComputerDetails.Manufacturer = "HP"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-CIMInstance -ClassName "MS_SystemInformation" -NameSpace "root\WMI").BaseBoardProduct.Trim()
}
"*Dell*" {
$ComputerDetails.Manufacturer = "Dell"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-CIMInstance -ClassName "MS_SystemInformation" -NameSpace "root\WMI").SystemSku.Trim()
[string]$OEMString = Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty OEMStringArray
$ComputerDetails.FallbackSKU = [regex]::Matches($OEMString, '\[\S*]')[0].Value.TrimStart("[").TrimEnd("]")
}
"*Lenovo*" {
$ComputerDetails.Manufacturer = "Lenovo"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystemProduct" | Select-Object -ExpandProperty Version).Trim()
$ComputerDetails.SystemSKU = ((Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).SubString(0, 4)).Trim()
}
"*Panasonic*" {
$ComputerDetails.Manufacturer = "Panasonic Corporation"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-CIMInstance -ClassName "MS_SystemInformation" -NameSpace "root\WMI").BaseBoardProduct.Trim()
}
"*Viglen*" {
$ComputerDetails.Manufacturer = "Viglen"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-WmiObject -Class "Win32_BaseBoard" | Select-Object -ExpandProperty SKU).Trim()
}
"*AZW*" {
$ComputerDetails.Manufacturer = "AZW"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-CIMInstance -ClassName "MS_SystemInformation" -NameSpace root\WMI).BaseBoardProduct.Trim()
}
"*Fujitsu*" {
$ComputerDetails.Manufacturer = "Fujitsu"
$ComputerDetails.Model = (Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty Model).Trim()
$ComputerDetails.SystemSKU = (Get-WmiObject -Class "Win32_BaseBoard" | Select-Object -ExpandProperty SKU).Trim()
}
}
# Handle overriding computer details if debug mode and additional parameters was specified
if ($Script:PSCmdlet.ParameterSetName -like "Debug") {
if (-not ([string]::IsNullOrEmpty($Manufacturer))) {
$ComputerDetails.Manufacturer = $Manufacturer
}
if (-not ([string]::IsNullOrEmpty($ComputerModel))) {
$ComputerDetails.Model = $ComputerModel
}
if (-not ([string]::IsNullOrEmpty($SystemSKU))) {
$ComputerDetails.SystemSKU = $SystemSKU
}
}
# Handle output to log file for computer details
Write-CMLogEntry -Value " - Computer manufacturer determined as: $($ComputerDetails.Manufacturer)" -Severity 1
Write-CMLogEntry -Value " - Computer model determined as: $($ComputerDetails.Model)" -Severity 1
# Handle output to log file for computer SystemSKU
if (-not ([string]::IsNullOrEmpty($ComputerDetails.SystemSKU))) {
Write-CMLogEntry -Value " - Computer SystemSKU determined as: $($ComputerDetails.SystemSKU)" -Severity 1
} else {
Write-CMLogEntry -Value " - Computer SystemSKU determined as: <null>" -Severity 2
}
# Handle output to log file for Fallback SKU
if (-not ([string]::IsNullOrEmpty($ComputerDetails.FallBackSKU))) {
Write-CMLogEntry -Value " - Computer Fallback SystemSKU determined as: $($ComputerDetails.FallBackSKU)" -Severity 1
}
# Handle return value from function
return $ComputerDetails
}
function Get-ComputerSystemType {
$ComputerSystemType = Get-WmiObject -Class "Win32_ComputerSystem" | Select-Object -ExpandProperty "Model"
if ($ComputerSystemType -notin @("Virtual Machine", "VMware Virtual Platform", "VirtualBox", "HVM domU", "KVM", "VMWare7,1")) {
Write-CMLogEntry -Value " - Supported computer platform detected, script execution allowed to continue" -Severity 1
} else {
if ($Script:PSCmdlet.ParameterSetName -like "Debug") {
Write-CMLogEntry -Value " - Unsupported computer platform detected, virtual machines are not supported but will be allowed in DebugMode" -Severity 2
} else {
Write-CMLogEntry -Value " - Unsupported computer platform detected, virtual machines are not supported" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
}
}
}
function Test-ComputerDetails {
param (
[parameter(Mandatory = $true, HelpMessage = "Specify the computer details object from Get-ComputerDetails function.")]
[ValidateNotNullOrEmpty()]
[PSCustomObject]$InputObject
)
# Construct custom object for computer details validation
$Script:ComputerDetection = [PSCustomObject]@{
"ModelDetected" = $false
"SystemSKUDetected" = $false
}
if (($InputObject.Model -ne $null) -and (-not ([System.String]::IsNullOrEmpty($InputObject.Model)))) {
Write-CMLogEntry -Value " - Computer model detection was successful" -Severity 1
$ComputerDetection.ModelDetected = $true
}
if (($InputObject.SystemSKU -ne $null) -and (-not ([System.String]::IsNullOrEmpty($InputObject.SystemSKU)))) {
Write-CMLogEntry -Value " - Computer SystemSKU detection was successful" -Severity 1
$ComputerDetection.SystemSKUDetected = $true
}
if (($ComputerDetection.ModelDetected -eq $false) -and ($ComputerDetection.SystemSKUDetected -eq $false)) {
Write-CMLogEntry -Value " - Computer model and SystemSKU values are missing, script execution is not allowed since required values to continue could not be gathered" -Severity 3
# Throw terminating error
$ErrorRecord = New-TerminatingErrorRecord -Message ([string]::Empty)
$PSCmdlet.ThrowTerminatingError($ErrorRecord)
} else {
Write-CMLogEntry -Value " - Computer details successfully verified" -Severity 1
}
}
function Set-ComputerDetectionMethod {
if ($ComputerDetection.SystemSKUDetected -eq $true) {
Write-CMLogEntry -Value " - Determined primary computer detection method: SystemSKU" -Severity 1
return "SystemSKU"
} else {
Write-CMLogEntry -Value " - Determined fallback computer detection method: ComputerModel" -Severity 1
return "ComputerModel"
}
}
function Compare-BIOSVersion {
param (
[parameter(Mandatory = $false, HelpMessage = "Current available BIOS version.")]
[ValidateNotNullOrEmpty()]
[string]$AvailableBIOSVersion,
[parameter(Mandatory = $false, HelpMessage = "Current available BIOS revision date.")]
[string]$AvailableBIOSReleaseDate,
[parameter(Mandatory = $true, HelpMessage = "Current available BIOS version.")]
[ValidateNotNullOrEmpty()]
[string]$ComputerManufacturer
)
if ($ComputerManufacturer -match "Dell") {
# Obtain current BIOS release
$CurrentBIOSVersion = (Get-WmiObject -Class Win32_BIOS | Select-Object -ExpandProperty SMBIOSBIOSVersion).Trim()
Write-CMLogEntry -Value "Current BIOS release detected as $($CurrentBIOSVersion)." -Severity 1
Write-CMLogEntry -Value "Available BIOS release deteced as $($AvailableBIOSVersion)." -Severity 1
# Determine Dell BIOS revision format
if ($CurrentBIOSVersion -like "*.*.*") {
# Compare current BIOS release to available
if ([System.Version]$AvailableBIOSVersion -gt [System.Version]$CurrentBIOSVersion) {
# Write output to task sequence variable
if ($Script:PSCmdlet.ParameterSetName -notlike "Debug") {
$TSEnvironment.Value("NewBIOSAvailable") = $true
}
Write-CMLogEntry -Value "A new version of the BIOS has been detected. Current release $($CurrentBIOSVersion) will be replaced by $($AvailableBIOSVersion)." -Severity 1
}
} elseif ($CurrentBIOSVersion -like "A*") {
# Compare current BIOS release to available
if ($AvailableBIOSVersion -like "*.*.*") {
# Assume that the bios is new as moving from Axx to x.x.x formats
# Write output to task sequence variable
if ($Script:PSCmdlet.ParameterSetName -notlike "Debug") {
$TSEnvironment.Value("NewBIOSAvailable") = $true
}
Write-CMLogEntry -Value "A new version of the BIOS has been detected. Current release $($CurrentBIOSVersion) will be replaced by $($AvailableBIOSVersion)." -Severity 1
} elseif ($AvailableBIOSVersion -gt $CurrentBIOSVersion) {
# Write output to task sequence variable
if ($Script:PSCmdlet.ParameterSetName -notlike "Debug") {
$TSEnvironment.Value("NewBIOSAvailable") = $true
}
Write-CMLogEntry -Value "A new version of the BIOS has been detected. Current release $($CurrentBIOSVersion) will be replaced by $($AvailableBIOSVersion)." -Severity 1
}
}
}
if ($ComputerManufacturer -match "Lenovo") {
# Obtain current BIOS release
$CurrentBIOSReleaseDate = ((Get-WmiObject -Class Win32_BIOS | Select-Object -Property *).ReleaseDate).SubString(0, 8)
Write-CMLogEntry -Value "Current BIOS release date detected as $($CurrentBIOSReleaseDate)." -Severity 1
Write-CMLogEntry -Value "Available BIOS release date detected as $($AvailableBIOSReleaseDate)." -Severity 1
# Compare current BIOS release to available
if ($AvailableBIOSReleaseDate -gt $CurrentBIOSReleaseDate) {
# Write output to task sequence variable
if ($Script:PSCmdlet.ParameterSetName -notlike "Debug") {
$TSEnvironment.Value("NewBIOSAvailable") = $true
}
Write-CMLogEntry -Value "A new version of the BIOS has been detected. Current date release dated $($CurrentBIOSReleaseDate) will be replaced by release $($AvailableBIOSReleaseDate)." -Severity 1
}
}
if ($ComputerManufacturer -match "Hewlett-Packard|HP") {
# Obtain current BIOS release
$CurrentBIOSProperties = (Get-WmiObject -Class Win32_BIOS | Select-Object -Property *)
# Update version formatting
$AvailableBIOSVersion = $AvailableBIOSVersion.TrimEnd(".")
$AvailableBIOSVersion = $AvailableBIOSVersion.Split(" ")[0]
# Detect new versus old BIOS formats
switch -wildcard ($($CurrentBIOSProperties.SMBIOSBIOSVersion)) {
"*ver*" {
if ($CurrentBIOSProperties.SMBIOSBIOSVersion -match '.F.\d+$') {