-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssetSelfReport.ps1
More file actions
1885 lines (1730 loc) · 113 KB
/
Copy pathAssetSelfReport.ps1
File metadata and controls
1885 lines (1730 loc) · 113 KB
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
param (
[Object]$ConfigFile=''
)
Clear-Host;
########################################################################################################################################################################################################
# Remove Stale Variables
########################################################################################################################################################################################################
Remove-Variable -Name DataHashTable -ErrorAction 'SilentlyContinue';
Remove-Variable -Name DataObject -ErrorAction 'SilentlyContinue';
Remove-Variable -Name Record -ErrorAction 'SilentlyContinue';
Remove-Variable -Name EmailParams -ErrorAction 'SilentlyContinue';
Remove-Variable -Name Config -ErrorAction 'SilentlyContinue';
########################################################################################################################################################################################################
# Junk serial detection helper
########################################################################################################################################################################################################
function Test-InvalidInventorySerial {
param([string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) {
return $true
}
$v = $Value.Trim()
if (
$v -match '^To be filled by O\.?E\.?M\.?$' -or
$v -match '^Default string$' -or
$v -match '^System Serial Number$' -or
$v -match '^Unknown$' -or
$v -match '^None$'
) {
return $true
}
return $false
}
########################################################################################################################################################################################################
# Static Variables
########################################################################################################################################################################################################
If (!$ConfigFile) {
Write-Error "You did not provide a config file!";
Write-Error "Use the flag '-ConfigFile' and provide a completed config."
Write-Error "Exiting..."
Start-Sleep -Seconds 10; Exit 1;
}
$Config = (Get-Content $ConfigFile) | ConvertFrom-Json;
$EmailParams = @{
From=$Config.EmailParams.From;
To=$Config.EmailParams.To;
SMTPServer=$Config.EmailParams.SMTPServer;
port=$Config.EmailParams.Port;
}
$LocalFileDir = $Config.LocalFileDir;
$LogFileDir = $Config.LogFileDir;
$RamAlertLog = "$LocalFileDir\LowRamAlert.json";
$StorageAlertLog = "$LocalFileDir\LowStorageAlert.json";
$RecordFileDir = $Config.RecordFileDir;
$DellApi = $Config.DellApi;
$Snipe = $Config.Snipe;
$DailyPowerOnList = $Config.DailyPowerOnList;
$KeyFile = $Config.DellBios.KeyFile;
$OldPwdFile = $Config.DellBios.OldPwdFile;
$NewPwdFile = $Config.DellBios.NewPwdFile;
# Script Version
$ScriptVersion = "1.9";
$StartTime = Get-Date;
$Today = Get-Date -UFormat "%d-%b-%Y";
$DeviceName = hostname;
[HashTable]$DataHashTable = @{};
$Win32_BIOS = Get-WmiObject -Class Win32_BIOS
$Win32_ComputerSystemProduct = Get-WmiObject -Class Win32_ComputerSystemProduct
$Win32_BaseBoard = Get-WmiObject -Class Win32_BaseBoard
$BiosSerial = ($Win32_BIOS.SerialNumber | Out-String).Trim()
$UUID = ($Win32_ComputerSystemProduct.UUID | Out-String).Trim()
$BoardSerial = ($Win32_BaseBoard.SerialNumber | Out-String).Trim()
# Optional override file (keep your existing logic)
$OverrideSerial = $null
if (Test-Path -Path 'C:\CCCJ\ASR\sn.txt' -PathType Leaf) {
$OverrideSerial = (Get-Content -Path 'C:\CCCJ\ASR\sn.txt' | Select-Object -First 1).Trim()
}
if (-not (Test-InvalidInventorySerial $OverrideSerial)) {
$SerialNumber = $OverrideSerial
}
elseif (-not (Test-InvalidInventorySerial $BiosSerial)) {
$SerialNumber = $BiosSerial
}
elseif (
-not [string]::IsNullOrWhiteSpace($UUID) -and
$UUID -notmatch '^FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF$' -and
$UUID -notmatch '^00000000-0000-0000-0000-000000000000$'
) {
$SerialNumber = $UUID
}
elseif (-not (Test-InvalidInventorySerial $BoardSerial)) {
$SerialNumber = "MB-$BoardSerial"
}
else {
$SerialNumber = $DeviceName
}
$RandomNumber = Get-Random -Minimum 0 -Maximum 300;
$SystemInformation = Get-WmiObject -Namespace root\wmi -Class MS_SystemInformation;
$SoftwareLicensingServiceInfo = Get-WmiObject -query 'select * from SoftwareLicensingService';
# List of default, erroneous, and redundant apps that may be installed that we do not need listed under "installed software".
# The script will still notify you if install status changes for these, but will not list these apps in SnipeIT.
$DefaultSoftware = @(
"Alertus Desktop"
"Adobe Genuine Service"
"AMD Settings - Branding"
"Adobe Refresh Manager"
"ConfigMgr Client Setup Bootstrap"
"Dropbox Update Helper"
"Dynamic Application Loader Host Interface Service"
"Intel(R) Chipset Device Software"
"Intel(R) Icls"
"Intel(R) LMS"
"Intel(R) Management Engine Components"
"Intel(R) Management Engine Driver"
"Intel(R) Processor Graphics"
"Intel(R) OEM Extension"
"Intel(R) Rapid Storage Technology"
"Intel(R) Serial IO"
"Intel(R) Trusted Connect Service Client x64"
"Intel(R) Trusted Connect Service Client x86"
"Intel(R) Trusted Connect Services Client"
"Intel(R) Wireless Manageability Driver"
"Intel(R) Wireless Manageability Driver Extension"
"Intel Optane Pinning Explorer Extensions"
"Maxx Audio Installer (x64)"
"Microsoft Edge"
"Microsoft Edge Update"
"Microsoft Edge WebView2 Runtime"
"Microsoft Mouse and Keyboard Center"
"Microsoft OneDrive"
"Microsoft Policy Platform"
"Microsoft Update Health Tools"
"Microsoft VC++ redistributables repacked."
"Microsoft Visual C++ 2010 x64 Redistributable"
"Microsoft Visual C++ 2010 x86 Redistributable"
"Microsoft Visual C++ 2012 Redistributable (x64)"
"Microsoft Visual C++ 2012 Redistributable (x86)"
"Microsoft Visual C++ 2012 x64 Additional Runtime"
"Microsoft Visual C++ 2012 x64 Minimum Runtime"
"Microsoft Visual C++ 2012 x86 Additional Runtime"
"Microsoft Visual C++ 2012 x86 Minimum Runtime"
"Microsoft Visual C++ 2013 Redistributable (x64)"
"Microsoft Visual C++ 2013 Redistributable (x86)"
"Microsoft Visual C++ 2013 x64 Additional Runtime"
"Microsoft Visual C++ 2013 x64 Minimum Runtime"
"Microsoft Visual C++ 2013 x86 Additional Runtime"
"Microsoft Visual C++ 2013 x86 Minimum Runtime"
"Microsoft Visual C++ 2015"
"Microsoft Visual C++ 2015"
"Microsoft Visual C++ 2019 X64 Additional Runtime"
"Microsoft Visual C++ 2019 X64 Minimum Runtime"
"Microsoft Visual C++ 2019 X86 Additional Runtime"
"Microsoft Visual C++ 2019 X86 Minimum Runtime"
"Mozilla Maintenance Service"
"Office 16 Click-to-Run Extensibility Component"
"Office 16 Click-to-Run Licensing Component"
"Office 16 Click-to-Run Localization Component"
"Realtek Audio COM Components"
"Realtek Audio Driver"
"Realtek High Definition Audio Driver"
"Software Update Wizard (Redist)"
"Teams Machine-Wide Installer"
"Windows Firewall Configuration Provider"
);
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Begin Custom Code
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
If ($DeviceName -eq "CCCJ-FS01") {
$LogFileDir = $LogFileDir -replace "c",'R:';
$RecordFileDir = $RecordFileDir -replace "\\\\fs01.criminology.fsu.edu",'R:';
}
If (!$SerialNumber -OR $SerialNumber -eq ' ') {
If (Test-Path -Path 'C:\CCCJ\ASR\sn.txt' -PathType Leaf) { $SerialNumber = Get-Content -Path 'C:\CCCJ\ASR\sn.txt'; }
}
If ($DeviceName -eq 'EPS-102D-PC01') {
$RandomNumber = 0;
}
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# End Custom Code
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
########################################################################################################################################################################################################
# Static Variables
########################################################################################################################################################################################################
#$DataHashTable.Add('SerialNumber', $SerialNumber);
$DataHashTable.Add('SerialNumber', $SerialNumber)
$Win32_ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem;
$CsvFile = "$RecordFileDir\$($SerialNumber).csv";
$DateDir = Get-Date -UFormat "%Y-%B";
$LogFileDir = "$LogFileDir\$DateDir\$($DeviceName)";
$LogFileDate = Get-Date -UFormat "%d-%b-%Y";
$LogFile = "$LogFileDir\$($SerialNumber)_$($DeviceName)_$($LogFileDate)_SelfReport.log";
$StringHasher = [System.Security.Cryptography.HashAlgorithm]::Create('sha256');
$EmailParams.Add('Subject','');
$EmailParams.Add('Body','');
$CustomValues = @{};
#Get UUID
$UUID = (Get-WmiObject -Class Win32_ComputerSystemProduct).UUID
$DataHashTable.Add('UUID', $UUID);
#Add Script Version
$DataHashTable.Add('ScriptVersion', $ScriptVersion);
#Get Bitlocker Status
$BitLockerRaw = Manage-BDE -Status | Out-String
$BitLockerVersionLine = $BitLockerRaw -split "`r?`n" | Where-Object {$_ -match 'BitLocker Version:'} | Select-Object -First 1
$BitLockerVersion = ($BitLockerVersionLine -replace 'BitLocker Version:\s*','') -as [string]
$DataHashTable.Add('BitLockerVersion', $BitLockerVersion);
$BitLockerLines = $BitLockerRaw -split "`r?`n" | Where-Object {
$_ -match 'Conversion Status:' -or
$_ -match 'Percentage Encrypted:' -or
$_ -match 'Encryption Method:' -or
$_ -match 'Protection Status:'
}
$BitLockerBDE = $BitLockerLines -join "`n"
$BitLockerVolRaw = Get-BitLockerVolume | ForEach-Object {
$mount = $_.MountPoint
$_.KeyProtector | ForEach-Object {
"Drive: $mount | KeyProtectorId: $($_.KeyProtectorId) | KeyProtectorType: $($_.KeyProtectorType)"
}
}
$BitLockerVolume = $BitLockerVolRaw -join "`n"
$BitLockerSummary = ($BitLockerBDE, $BitLockerVolume) -join "`n"
$DataHashTable.Add('BitLockerSummary', $BitLockerSummary);
#Get Secure Boot Status
Try {
$SecureBootEnabled = Confirm-SecureBootUEFI -ErrorAction Stop
If ($SecureBootEnabled -eq $true) {
$SecureBootStatus = "Enabled"
} ElseIf ($SecureBootEnabled -eq $false) {
$SecureBootStatus = "Disabled"
} Else {
$SecureBootStatus = "Unknown"
}
} Catch {
$SecureBootStatus = "Not Supported (Legacy BIOS)"
}
$DataHashTable.Add('SecureBootStatus', $SecureBootStatus);
# --- Robust Secure Boot Certificate Expiry ---
Write-Host "Secure Boot Certificate Expiry" -ForegroundColor Green
$SecureBootCertInfo = ""
# GUIDs from UEFI spec
$GUID_X509 = [guid]'a5c059a1-94e4-4aa7-87b5-ab155c2bf072' # EFI_CERT_X509_GUID
$GUID_SHA256 = [guid]'c1c41626-504c-4092-aca9-41f936934328' # EFI_CERT_SHA256_GUID
$GUID_PKCS7 = [guid]'4aafd29d-68df-49ee-8aa9-347d375665a7' # EFI_CERT_TYPE_PKCS7_GUID'
function Read-UInt32LE([byte[]]$b, [int]$o) { [BitConverter]::ToUInt32($b, $o) }
function Get-Guid([byte[]]$b, [int]$o) {
$slice = New-Object byte[] 16
[Buffer]::BlockCopy($b, $o, $slice, 0, 16)
# Guid(byte[]) ctor expects little-endian fields as in UEFI storage
return New-Object System.Guid(,$slice)
}
function Parse-Db {
param([byte[]]$Raw)
$result = New-Object System.Collections.Generic.List[object]
$ofs = 0
$HDR = 16 + 4 + 4 + 4 # Type(16) + ListSize + HeaderSize + SigSize
while ($ofs -le $Raw.Length - $HDR) {
$sigType = Get-Guid $Raw $ofs; $ofs += 16
$listSize = Read-UInt32LE $Raw $ofs; $ofs += 4
$hdrSize = Read-UInt32LE $Raw $ofs; $ofs += 4
$sigSize = Read-UInt32LE $Raw $ofs; $ofs += 4
# Bounds check
$listStart = $ofs - $HDR
$listEnd = $listStart + $listSize
if ($listSize -lt $HDR -or $listEnd -gt $Raw.Length -or $sigSize -lt 16) {
# Malformed list; bail out of this list
$ofs = $listEnd
continue
}
# Skip signature header (rarely used)
$ofs += $hdrSize
# Walk EFI_SIGNATURE_DATA entries
while ($ofs + $sigSize -le $listEnd) {
# First 16 bytes is Owner GUID, remainder is SignatureData
$owner = Get-Guid $Raw $ofs
$ofsOwnerEnd = $ofs + 16
$dataLen = $sigSize - 16
$sigData = New-Object byte[] $dataLen
[Buffer]::BlockCopy($Raw, $ofsOwnerEnd, $sigData, 0, $dataLen)
$ofs += $sigSize
switch ($true) {
{ $sigType -eq $GUID_X509 } {
try {
$x = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,$sigData)
$result.Add([pscustomobject]@{
Type = 'X509'
OwnerGuid = $owner
Subject = $x.Subject
Issuer = $x.Issuer
NotAfter = $x.NotAfter
Thumbprint = $x.Thumbprint
})
} catch {}
}
{ $sigType -eq $GUID_PKCS7 } {
try {
Add-Type -AssemblyName System.Security # for Pkcs
Add-Type -AssemblyName System.Security.Cryptography
$cms = New-Object System.Security.Cryptography.Pkcs.SignedCms
$cms.Decode($sigData)
foreach ($c in $cms.Certificates) {
$result.Add([pscustomobject]@{
Type = 'PKCS7-Cert'
OwnerGuid = $owner
Subject = $c.Subject
Issuer = $c.Issuer
NotAfter = $c.NotAfter
Thumbprint = $c.Thumbprint
})
}
} catch {}
}
{ $sigType -eq $GUID_SHA256 } {
# Hash allow-list entry; no expiry
$result.Add([pscustomobject]@{
Type = 'SHA256-Hash'
OwnerGuid = $owner
Subject = '<hash entry>'
Issuer = ''
NotAfter = $null
Thumbprint = ([BitConverter]::ToString($sigData) -replace '-', '')
})
}
default {
# Unknown/other signature type; record basics
$result.Add([pscustomobject]@{
Type = "Other:$sigType"
OwnerGuid = $owner
Subject = ''
Issuer = ''
NotAfter = $null
Thumbprint = ''
})
}
}
}
# move to next list (in case of padding/misalignment)
$ofs = $listEnd
}
# De-duplicate by Thumbprint when present (PKCS7 can contain repeats)
$seen = @{}
$unique = foreach ($r in $result) {
$key = if ($r.Thumbprint) { $r.Type + ':' + $r.Thumbprint } else { [guid]::NewGuid().ToString() }
if (-not $seen.ContainsKey($key)) {
$seen[$key] = $true
$r
}
}
return ,$unique
}
try {
if ($SecureBootStatus -in @('Enabled','Disabled')) {
$raw = (Get-SecureBootUEFI -Name db -ErrorAction Stop).Bytes
Write-Host " Parsing EFI signature lists ($($raw.Length) bytes)..." -ForegroundColor Cyan
$entries = Parse-Db -Raw $raw
$certs = $entries | Where-Object { $_.Type -in 'X509','PKCS7-Cert' }
$hashes = $entries | Where-Object { $_.Type -eq 'SHA256-Hash' }
Write-Host (" Found {0} certificate(s), {1} hash entry/entries" -f $certs.Count, $hashes.Count) -ForegroundColor Cyan
Write-Host ""
if ($certs.Count -gt 0) {
$today = Get-Date
$lines = @()
foreach ($c in ($certs | Sort-Object Subject, NotAfter -Unique)) {
$days = if ($c.NotAfter) { ($c.NotAfter - $today).Days } else { $null }
$expiry = if ($c.NotAfter) { $c.NotAfter.ToString('yyyy-MM-dd') } else { 'N/A' }
$subjectCN = ($c.Subject -replace '^.*CN=([^,]+).*$','$1')
if ($days -lt 0) { $status = "EXPIRED"; $color = "Red" }
elseif ($days -lt 180) { $status = "EXPIRING SOON"; $color = "Yellow" }
else { $status = "Valid"; $color = "Green" }
Write-Host (" {0}" -f $subjectCN) -ForegroundColor White
Write-Host (" Expires: {0} ({1}{2})" -f $expiry, $status, $(if ($days -ne $null) { ", $days days" } else { "" })) -ForegroundColor $color
$lines += ("{0} : {1} ({2}{3})" -f $subjectCN, $expiry, $status, $(if ($days -ne $null) { ", $days days" } else { "" }))
}
# Your summary sink
$SecureBootCertInfo = $lines -join "`n"
# Your early-2026 warning:
$exp26 = $certs | Where-Object { $_.NotAfter -and $_.NotAfter.Year -eq 2026 -and $_.NotAfter.Month -le 6 }
if ($exp26.Count -gt 0) {
Write-Host ""
Write-Host (" WARNING: Found {0} certificate(s) expiring in early 2026!" -f $exp26.Count) -ForegroundColor Red
}
}
else {
$SecureBootCertInfo = "No X.509 certificates present (DB may contain only hashes)."
Write-Host " $SecureBootCertInfo" -ForegroundColor Yellow
}
} else {
$SecureBootCertInfo = "N/A (Secure Boot not supported)"
Write-Host " $SecureBootCertInfo" -ForegroundColor Gray
}
} catch {
$SecureBootCertInfo = "Unable to read/parse Secure Boot DB ($($_.Exception.Message))"
Write-Host " $SecureBootCertInfo" -ForegroundColor Yellow
}
# --- Pick a single meaningful value for Snipe-IT (text + date) ---
function Get-ConciseMicrosoftSecureBootExpiry {
param(
[Parameter(Mandatory)] [object[]] $Certs, # entries with Subject / NotAfter
[Parameter(Mandatory)] [string] $SecureBootStatus # "Enabled" | "Disabled" | etc.
)
if (-not $Certs -or $Certs.Count -eq 0) {
return [pscustomobject]@{
Text = 'No X.509 certificates (hash-only DB)'
Date = $null
}
}
# Microsoft CAs relevant to Windows boot trust
$msCerts = $Certs | Where-Object {
$_.Subject -match 'Microsoft' -and
(
$_.Subject -match 'Windows\s+Production\s+PCA' -or
$_.Subject -match '\bUEFI\s+CA\b' -or
$_.Subject -match 'Option\s+ROM\s+UEFI\s+CA'
)
}
if (-not $msCerts) {
return [pscustomobject]@{
Text = 'No Microsoft UEFI/Boot CAs found'
Date = $null
}
}
# Earliest expiry among MS CAs = practical “deadline”
$earliest = $msCerts | Sort-Object NotAfter | Select-Object -First 1
$today = Get-Date
$days = if ($earliest.NotAfter) { ($earliest.NotAfter - $today).Days } else { $null }
$expiry = if ($earliest.NotAfter) { $earliest.NotAfter.ToString('yyyy-MM-dd') } else { 'N/A' }
$subjectCN = ($earliest.Subject -replace '^.*CN=([^,]+).*$','$1')
$status =
if ($days -eq $null) { 'N/A' }
elseif ($days -lt 0) { 'EXPIRED' }
elseif ($days -lt 180) { 'EXPIRING SOON' }
else { 'Valid' }
$sbFlag = if ($SecureBootStatus -eq 'Enabled') { '' } else { '[SB OFF] ' }
[pscustomobject]@{
Text = ("{0}{1} : {2} ({3}{4})" -f $sbFlag, $subjectCN, $expiry, $status,
$(if ($days -ne $null) { ", $days days" } else { "" }))
Date = $earliest.NotAfter # DateTime (or $null)
}
}
# Produce BOTH fields the rest of the script will use
$sbSummary = Get-ConciseMicrosoftSecureBootExpiry -Certs $certs -SecureBootStatus $SecureBootStatus
# Long contextual text
$DataHashTable['SecureBootCertExpiry'] = $sbSummary.Text
# ISO date string (or empty if no date)
$DataHashTable['SecureBootCertExpiryDate'] = if ($sbSummary.Date) {
$sbSummary.Date.ToString('yyyy-MM-dd')
} else {
''
}
Write-Host (" Snipe-IT Secure Boot Cert Expiry (text): {0}" -f $DataHashTable['SecureBootCertExpiry']) -ForegroundColor Cyan
Write-Host (" Snipe-IT Secure Boot Cert Expiry Date : {0}" -f $DataHashTable['SecureBootCertExpiryDate']) -ForegroundColor Cyan
# --- Secure Boot Compliance classification ---
# Helper: read DB explicitly to test for 2023 CAs in Default DB (even if Active DB was parsed)
$entriesDefault = $null
try {
$rawDefault = (Get-SecureBootUEFI -Name dbDefault -ErrorAction Stop).Bytes
if ($rawDefault -and $rawDefault.Length -gt 0) {
$entriesDefault = Parse-Db -Raw $rawDefault
}
} catch {}
# Patterns for Microsoft CA subjects
$reMS2011 = 'Microsoft.*(UEFI\s*CA\s*2011|Windows\s+Production\s+PCA\s+2011)'
$reMS2023 = '(Windows\s+UEFI\s+CA\s+2023|Microsoft\s+UEFI\s+CA\s+2023|Microsoft\s+Corporation\s+KEK\s+2K\s+CA\s+2023|Microsoft\s+Option\s+ROM\s+UEFI\s+CA\s+2023)'
# Active DB (parsed to $certs earlier)
$ms2011Active = @($certs | Where-Object { $_.Subject -match $reMS2011 })
$ms2023Active = @($certs | Where-Object { $_.Subject -match $reMS2023 })
# Default DB (explicit check regardless of which source we parsed to $certs)
$ms2023Default = @($entriesDefault | Where-Object { $_.Subject -match $reMS2023 })
# Earliest 2011 expiry we can see (Active first; if none, consider Default)
$earliest2011 =
@($ms2011Active + ($entriesDefault | Where-Object { $_.Subject -match $reMS2011 })) |
Where-Object { $_.NotAfter } |
Sort-Object NotAfter |
Select-Object -First 1
$today = Get-Date
$daysTo2011 = if ($earliest2011 -and $earliest2011.NotAfter) { ($earliest2011.NotAfter - $today).Days } else { $null }
function Get-SBCompliance {
param(
[string] $SecureBootStatus,
[array] $Ms2023Active,
[array] $Ms2023Default,
[Nullable[int]] $DaysTo2011
)
switch ($SecureBootStatus) {
'Enabled' {
if ($Ms2023Active.Count -gt 0) {
return 'Compliant - 2023 CAs Active'
}
elseif ($Ms2023Default.Count -gt 0) {
# Firmware will repopulate Active DB from Default DB on firmware/OS update or specific tasks
return 'Pending - 2023 CA present in Default DB (Active DB still 2011)'
}
else {
if ($DaysTo2011 -eq $null) {
return 'At Risk - 2023 CA missing; 2011 expiry unknown'
}
elseif ($DaysTo2011 -lt 0) {
return 'At Risk - 2011 CAs expired; 2023 CA missing'
}
elseif ($DaysTo2011 -lt 180) {
return ('At Risk - 2011 CAs expiring soon ({0} days); 2023 CA missing' -f $DaysTo2011)
}
else {
return ('At Risk - 2023 CA missing; 2011 CAs expire in {0} days' -f $DaysTo2011)
}
}
}
'Disabled' {
return 'Secure Boot Disabled - Cert validity irrelevant'
}
'Not Supported (Legacy BIOS)' {
return 'Not Supported (Legacy BIOS) - Compliance N/A'
}
default {
# Includes 'Unknown' or cases where DB is unavailable (Setup Mode or keys cleared)
return 'Unknown - DB not available (Setup Mode or keys not enrolled)'
}
}
}
$DataHashTable['SecureBootCompliance'] = Get-SBCompliance -SecureBootStatus $SecureBootStatus `
-Ms2023Active $ms2023Active `
-Ms2023Default $ms2023Default `
-DaysTo2011 $daysTo2011
Write-Host (" Secure Boot Compliance: {0}" -f $DataHashTable['SecureBootCompliance']) -ForegroundColor Cyan
#Get BIOS Release Date
If ($Win32_BIOS.ReleaseDate) {
Try {
$BiosReleaseDate = [System.Management.ManagementDateTimeConverter]::ToDateTime($Win32_BIOS.ReleaseDate);
$DataHashTable.Add('BiosReleaseDate', $BiosReleaseDate.ToString('yyyy-MM-dd'));
} Catch {
$DataHashTable.Add('BiosReleaseDate', '');
}
} Else {
$DataHashTable.Add('BiosReleaseDate', '');
}
$Domain = (Get-WmiObject -Class Win32_ComputerSystem).Domain;
$DataHashTable.Add('Domain', " $Domain");
#Get UI Language
$RegkeyResult = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\Language" -Name "Default"
if ($RegkeyResult.Default -eq "0809") {
$UILanguage = "en-GB"
} elseif ($RegkeyResult.Default -eq "0409") {
$UILanguage = "en-US"
}
$DataHashTable.Add('WindowsUILanguage', $UILanguage);
#Get Monitor Information
$MonitorData = Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorID
$MonitorInfo = ($MonitorData | ForEach-Object {
$Manufacturer = ($_.ManufacturerName | Where-Object {$_ -ne 0} | ForEach-Object {[char]$_}) -join ''
$Model = ($_.UserFriendlyName | Where-Object {$_ -ne 0} | ForEach-Object {[char]$_}) -join ''
$Serial = ($_.SerialNumberID | Where-Object {$_ -ne 0} | ForEach-Object {[char]$_}) -join ''
"$Manufacturer $Model [$Serial]"
}) -join "; "
$DataHashTable.Add('MonitorInfo', $MonitorInfo);
########################################################################################################################################################################################################
# Functions
########################################################################################################################################################################################################
Function WriteLog {
param( [String] $File = $LogFile, [String] $Log, [Object[]] $Data )
$Date = ((Get-Date -UFormat "%d-%b-%Y_%T") -replace ':', '-');
If ($LogFile) {
Switch -WildCard ($Log) {
"*success*" { Write-Host "[$Date] $Log" -f "Green"; Break; }
"*ERROR*" { Write-Host "[$Date] $Log" -f "Red"; Break; }
"*NEW*" { Write-Host "[$Date] $Log" -f "Yellow"; Break; }
Default { Write-Host "[$Date] $Log" -f "Magenta"; }
}
Add-Content $File "[$Date] $Log";
If ($Data) { ($Data | Out-String).Split("`n") | ForEach-Object { Write-Host $_; Add-Content $File (($_).Trim()); } }
}
}
Function EmailAlert {
param( [String] $Subject, [String] $Body )
$EmailParams.Subject = "$($Subject) - $($DeviceName)";
$EmailParams.Body = "Device: $($DeviceName)`n`n$($Body)";
Send-MailMessage @EmailParams;
}
Function GetHRSize {
param( [INT64] $bytes )
Process {
If ( $bytes -gt 1pb ) { "{0:N1}PB" -f ($bytes / 1pb) }
ElseIf ( $bytes -gt 1tb ) { "{0:N1}TB" -f ($bytes / 1tb) }
ElseIf ( $bytes -gt 1gb ) { "{0:N1}GB" -f ($bytes / 1gb) }
ElseIf ( $bytes -gt 1mb ) { "{0:N1}MB" -f ($bytes / 1mb) }
ElseIf ( $bytes -gt 1kb ) { "{0:N1}KB" -f ($bytes / 1kb) }
Else { "{0:N} Bytes" -f $bytes }
}
}
########################################################################################################################################################################################################
# Create Log Files and Directories
########################################################################################################################################################################################################
Function CheckFilesAndDirectories {
param( [Object] $Dir, [Object] $File)
Try {
$Dir | ForEach-Object { If (-NOT (Test-Path -Path $_)){ New-Item -ItemType Directory -Path $_; } }
$File | ForEach-Object { If (-NOT (Test-Path -Path $_ -PathType Leaf)) { New-Item -ItemType File -Path $_ -Force; } }
} Catch { WriteLog -Log "[ERROR] Error with Directories and Files." -Data $_; }
}
CheckFilesAndDirectories -Dir $LocalFileDir,$LogFileDir,$RecordFileDir -File $LogFile,$StorageAlertLog,$RamAlertLog;
########################################################################################################################################################################################################
# Package Requirements
########################################################################################################################################################################################################
#WriteLog -Log "Checking Required Packages...";
'NuGet' | ForEach-Object {
If (-NOT (Get-PackageProvider -ListAvailable -Name $_ -ErrorAction SilentlyContinue)) {
WriteLog -Log "[LOG] $_ Package not found. Installing...";
Install-PackageProvider $_ -Confirm:$false -Force:$true;
} Else {
$Installed = [String](Get-PackageProvider -ListAvailable -Name $_ | Select-Object -First 1).Version;
$Latest = [String](Find-PackageProvider -Name $_ | Sort-Object Version -Descending| Select-Object -First 1).version;
If ([System.Version]$Latest -gt [System.Version]$Installed) {
WriteLog -Log "[UPDATE] Updating $_...";
Install-PackageProvider $_ -Confirm:$false -Force:$true;
}
}
}
########################################################################################################################################################################################################
# Modules Requirements
########################################################################################################################################################################################################
#WriteLog -Log "Checking Required Modules...";
If ($Win32_ComputerSystem.Model -eq "Virtual Machine") {
$RequiredModules = 'SnipeitPS', 'PSWindowsUpdate', 'ActiveDirectory';
} ElseIf ($Win32_ComputerSystem.Manufacturer -like '*Dell*') {
$RequiredModules = 'SnipeitPS', 'DellBIOSProvider', 'ActiveDirectory', 'PSWindowsUpdate';
} Else {
$RequiredModules = 'SnipeitPS', 'ActiveDirectory', 'PSWindowsUpdate';
}
# Detect OS type once to decide how to install RSAT/AD tools
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
$isServer = $false
If ($osInfo) { $isServer = ($osInfo.ProductType -ne 1) }
$RequiredModules | ForEach-Object {
Try {
$Mdle = $_
If (!(Get-Module -ListAvailable -Name $Mdle)) {
WriteLog -Log "$Mdle not found. Installing..."
If ($Mdle -eq 'ActiveDirectory') {
If ($isServer) {
If (Get-Command -Name Install-WindowsFeature -ErrorAction SilentlyContinue) {
Try {
Install-WindowsFeature RSAT-AD-PowerShell -ErrorAction Stop
WriteLog -Log "Installed RSAT-AD-PowerShell via Install-WindowsFeature."
} Catch {
WriteLog -Log "[ERROR] Failed to install RSAT via Install-WindowsFeature. $_"
}
} Else {
WriteLog -Log "[WARN] Install-WindowsFeature not available on this Server. Skipping RSAT AD install."
}
} Else {
If (Get-Command -Name Add-WindowsCapability -ErrorAction SilentlyContinue) {
Try {
Add-WindowsCapability -Online -Name "Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0" -ErrorAction Stop
WriteLog -Log "Installed RSAT ActiveDirectory via Add-WindowsCapability."
} Catch {
WriteLog -Log "[ERROR] Failed to install RSAT via Add-WindowsCapability. $_"
}
} Else {
WriteLog -Log "[WARN] Add-WindowsCapability not available on this Client. Skipping RSAT AD install."
}
}
} Else {
Try {
Install-Module -Name $Mdle -Force -AllowClobber -ErrorAction Stop
WriteLog -Log "Installed PowerShell module $Mdle."
} Catch {
WriteLog -Log "[ERROR] Failed to Install-Module $Mdle. $_"
EmailAlert -Subject "[ERROR] Installing Module" -Body "$( $_ | Out-String)"
}
}
} Else {
Try {
$Latest = [String](Find-Module -Name $Mdle -ErrorAction SilentlyContinue | Sort-Object Version -Descending | Select-Object -First 1).version
$Installed = [String](Get-Module -ListAvailable -Name $Mdle | Select-Object -First 1).version
If ($Latest -and [System.Version]$Latest -gt [System.Version]$Installed) {
WriteLog -Log "[UPDATE] Updating $($Mdle)..."
Update-Module -Name $Mdle -Force
}
} Catch { }
}
Try { Import-Module -Name $Mdle -Force } Catch {
WriteLog -Log "[ERROR] Unable to Import $($Mdle) Module." -Data $_
EmailAlert -Subject "[ERROR] Importing Module" -Body "$( $_ | Out-String)"
}
} Catch { WriteLog -Log "[ERROR] $($_ | Out-String)" }
}
#WriteLog -Log "Requirements Installed and Loaded.";
########################################################################################################################################################################################################
# General Device Information
########################################################################################################################################################################################################
#WriteLog -Log "Gathering Device Information...";
$Location = "$(($DeviceName).Split("-")[0])-$(($DeviceName).Split("-")[1])";
$DataHashTable.Add('Location', $Location);
$DataHashTable.Add('DeviceName', $($DeviceName));
$DataHashTable.Add('LastReported', (Get-Date));
$DataHashTable.Add('LastReportedUnix', ([Math]::Round((Get-Date -UFormat %s),0)));
$DataHashTable.Add('Model', $Win32_ComputerSystem.Model);
$DataHashTable.Add('Manufacturer', "$($Win32_ComputerSystem.Manufacturer -replace " Inc.", '')");
$DataHashTable.Add('Bios', $Win32_BIOS.SMBIOSBIOSVersion);
$DataHashTable.Add('SKU', $SystemInformation.SystemSKU);
########################################################################################################################################################################################################
# Operating System Information
########################################################################################################################################################################################################
#WriteLog -Log "Gathering Operating System Information...";
$Win32_OperatingSystem = Get-WmiObject -Class Win32_OperatingSystem;
$DataHashTable.Add('OS', ($Win32_OperatingSystem.Name).Split("|")[0]);
$DataHashTable.Add('Build', $Win32_OperatingSystem.Version);
$Win_Version = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").DisplayVersion
$DataHashTable.Add('WindowsVersion', $Win_Version);
$DataHashTable.Add('BIOSWindowsLicenseKey', $SoftwareLicensingServiceInfo.OA3xOriginalProductKey);
If ($DataHashTable['OS'] -Contains "Server") { $ModelCatID = $Snipe.ServerCatID; }
########################################################################################################################################################################################################
# Bios Information
#################################f###################################################################################################
#WriteLog -Log "Gathering Bios Information...";
If (-NOT ($SerialNumber)) { EmailAlert -Subject "No BIOS Serial Number" -Body ($Win32_BIOS | Out-String); }
Try {
If ($DataHashTable['Manufacturer'] -eq 'Dell' -AND (Get-Item -Path "DellSmbios:\" -ErrorAction SilentlyContinue)) {
$BiosChanged = @();
$Key = Get-Content $KeyFile;
$OldBiosPwd = Get-Content $OldPwdFile | ConvertTo-SecureString -Key $Key
$OldBiosPwd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($OldBiosPwd);
$OldBiosPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($OldBiosPwd);
$NewBiosPwd = Get-Content $NewPwdFile | ConvertTo-SecureString -Key $Key
$NewBiosPwd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewBiosPwd);
$NewBiosPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($NewBiosPwd);
If ((Get-Item -Path "DellSmbios:\Security\IsAdminPasswordSet").CurrentValue -eq "True") {
Try { Set-Item -Path DellSmbios:\Security\AdminPassword "$NewBiosPwd" -Password "$NewBiosPwd" -ErrorAction Stop; }
Catch {
Try { Set-Item -Path DellSmbios:\Security\AdminPassword "$NewBiosPwd" -Password "$OldBiosPwd" -ErrorAction Stop; }
Catch { EmailAlert -Subject "Bios Password Change Error" -Body "Unable to change the bios password:`n$($_)"; }
}
} Else { Set-Item -Path "DellSmbios:\Security\AdminPassword" "$NewBiosPwd"; }
Function Set-DellBiosSetting {
param( [Object[]] $Setting, [String] $Value )
$CurrentValue = (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue;
#Write-Host $CurrentValue
If ($CurrentValue -ne $Value) {
$BiosChanged += $Setting.Attribute;
Try {
Set-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)" -Value $Value -Password $NewBiosPwd;
WriteLog -Log "Set Bios Setting: $($Setting.Attribute) to $($Value)."
} Catch { WriteLog -Log "Failed to Set Bios Setting." -Data $_; }
}
}
If ($BiosChanged.Count -gt 0) {
EmailAlert -Subject "Bios Configurations Changed" -Body "$($BiosChanged -join '`n')";
}
ForEach ($Category in (Get-ChildItem -Path "DellSmbios:\").Category) {
$CategorySettings = Get-ChildItem -Path "DellSmbios:\$($Category)" -WarningAction SilentlyContinue |
Select-Object Attribute,CurrentValue,PSChildName;
ForEach ($Setting in $CategorySettings) {
If ($DataHashTable['BootPathSecurity'] -eq 'UEFI') {
Switch ($Setting.Attribute) {
"BootList" { $DataHashTable.Add('BootMode', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"LegacyOrom" { $DataHashTable.Add('LegacyRoms', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"AttemptLegacyBoot" { $DataHashTable.Add('LegacyBoot', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"SecureBoot" { $DataHashTable.Add('SecureBoot', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
}
}
#Write-Host "$($Setting.Attribute) - $($Setting.CurrentValue)";
Switch ($Setting.Attribute) {
"MemorySpeed" { $MemorySpeed = $Setting.CurrentValue; }
"MemoryTechnology" { $MemoryType = $Setting.CurrentValue; }
"BootList" { $DataHashTable.Add('BootMode', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"LegacyOrom" { $DataHashTable.Add('LegacyRoms', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"AttemptLegacyBoot" { $DataHashTable.Add('LegacyBoot', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"SecureBoot" { $DataHashTable.Add('SecureBoot', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"UefiBootPathSecurity" { $DataHashTable.Add('BootPathSecurity', (Get-Item -Path "DellSmbios:\$($Setting.PSChildName)\$($Setting.Attribute)").CurrentValue); }
"EmbNic1" { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; }
"SfpNic" { Set-DellBiosSetting -Setting $Setting -Value "EnabledPXE"; }
"UefiNwStack" { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; }
"SmartErrors" { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; }
"TpmSecurity " { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; }
"TpmActivation" { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; }
"AcPwrRcvry" { Set-DellBiosSetting -Setting $Setting -Value "Last"; }
"DeepSleepCtrl" { Set-DellBiosSetting -Setting $Setting -Value "Disabled"; }
"WakeOnLan" { Set-DellBiosSetting -Setting $Setting -Value "LanWlan"; }
"BlockSleep" { Set-DellBiosSetting -Setting $Setting -Value "Disabled"; }
"ChassisIntrusionStatus" {
If ($Setting.CurrentValue -AND $Setting.CurrentValue -ne '' -AND $Setting.CurrentValue -ne "DoorClosed") {
EmailAlert -Subject "Chassis Intrustion Detected" -Body "Chassis Status: $($Setting.CurrentValue)";
Set-DellBiosSetting -Setting $Setting -Value "TripReset";
}
}
"WirelessLan" { If (-NOT (Get-WmiObject -Class win32_battery)) { Set-DellBiosSetting -Setting $Setting -Value "Disabled"; } }
"BluetoothDevice" { If (-NOT (Get-WmiObject -Class win32_battery)) { Set-DellBiosSetting -Setting $Setting -Value "Disabled"; } }
"AutoOn" { Set-DellBiosSetting -Setting $Setting -Value "SelectDays"; Break; }
"AutoOnHr" { Set-DellBiosSetting -Setting $Setting -Value "7"; Break; }
"AutoOnMn" { Set-DellBiosSetting -Setting $Setting -Value "0"; Break; }
"AutoOnMon" { If ($DailyPowerOnList -Contains $Location) { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; } Break; }
"AutoOnTue" { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; Break; }
"AutoOnWed" { If ($DailyPowerOnList -Contains $Location) { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; } Break; }
"AutoOnThur" { If ($DailyPowerOnList -Contains $Location) { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; } Break; }
"AutoOnFri" { If ($DailyPowerOnList -Contains $Location) { Set-DellBiosSetting -Setting $Setting -Value "Enabled"; } Break; }
}
}
}
}
} Catch {
WriteLog -Log "[ERROR] Issue Configuring Bios"
WriteLog -Log "$($_ | Out-String)";
EmailAlert -Subject "Error Configuring Bios" -Body "$($_ | Out-String)";
}
########################################################################################################################################################################################################
# Network Adapter Configurations
########################################################################################################################################################################################################
#WriteLog -Log "Gathering Network Adapter Information...";
$MacAddress = @();
$IpAddress = @();
$NetworkAdapters = @();
Get-NetAdapter | Where-Object { $_.Name -NotLike "*bluetooth*" } | ForEach-Object {
$IfcDesc = $_.InterfaceDescription -replace "\([^\)]+\)",'' -replace ' ',' ';
$NetworkAdapters += "[$($_.ifIndex)] $($_.LinkSpeed) - $($IfcDesc)";
$MacAddress += "$($_.MacAddress -replace '-',':')";
If ($_.Status -eq 'Up') {
$InterfaceAlias = "$($_.Name)";
$IpAddress += "$((Get-NetIpAddress | Where-Object { $_.AddressFamily -Like "IPv4" -and $_.InterfaceAlias -eq $InterfaceAlias; }).IPAddress)";
}
}
$MacAddress = $MacAddress -join "`n";
$IpAddress = $IpAddress -join "`n";
$NetworkAdapters = $NetworkAdapters -join "`n";
$DataHashTable.Add('IpAddress', $IpAddress);
$DataHashTable.Add('MacAddress', $MacAddress);
$DataHashTable.Add('NetworkAdapters', $NetworkAdapters);
# Custom MAC Address-based device identification
$BlackviewMacAddresses = @("68:1D:EF:50:47:02", "8C:EA:12:98:5D:AC");
$CollectedMacAddresses = $MacAddress -split "`n";
$MacMatch = $false;
ForEach ($CollectedMac in $CollectedMacAddresses) {
If ($BlackviewMacAddresses -contains $CollectedMac) {
$MacMatch = $true;
Break;
}
}
If ($MacMatch) {
WriteLog -Log "[LOG] Blackview MP60 MAC Address Detected. Overriding Model, Manufacturer and Serial Number.";
$DataHashTable['Model'] = "Blackview MP60";
$DataHashTable['Manufacturer'] = "Blackview";
$DataHashTable['SerialNumber'] = $DeviceName; # Use hostname as serial number for Blackview devices
}
Switch ((Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Sort-Object -Property Index | Where-Object { $_.IPAddress } | Select-Object -First 1).DHCPEnabled) {
"True" { $DataHashTable.Add('DHCP', "Enabled"); Break; }
"False" { $DataHashTable.Add('DHCP', "Disabled"); Break; }
}
########################################################################################################################################################################################################
# Group Access
########################################################################################################################################################################################################
#WriteLog -Log "Gathering Local Group Information...";
$LocalAdministrators = Get-LocalGroupMember -Group "Administrators";
$DataHashTable.Add('LocalAdmins', ($LocalAdministrators).Name -join "`n");
$RemoteDesktopUsers = Get-LocalGroupMember -Group "Remote Desktop Users";
$DataHashTable.Add('RemoteUsers', ($RemoteDesktopUsers).Name -join "`n");
# $LastUser = Get-WmiObject Win32_NetworkLoginProfile | Where{$_.LastLogon} | Sort LastLogon -Descending | Select-Object Name -first 1;
# Doesn't seem to work # $LastUser = (Get-CimInstance -ClassName Win32_ComputerSystem).Username
# Doesn't report anything when running as SYSTEM # $LastUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$LastUser = Get-ChildItem "c:\Users" | Sort-Object LastWriteTime -Descending | Select-Object Name, LastWriteTime -first 1
$DataHashTable.Add('LastUser', ($LastUser).Name);
########################################################################################################################################################################################################
# Uptime
########################################################################################################################################################################################################
#WriteLog -Log "Calculating Uptime...";
$Uptime = "";
$UptimeVal = ((Get-Date)-($Win32_OperatingSystem).ConvertToDateTime($Win32_OperatingSystem.LastBootUpTime));
Switch ($true) {
($UptimeVal.Days -gt 0) { $Uptime += "$($UptimeVal.Days)D:"; }
($UptimeVal.Hours -gt 0) { $Uptime += "$($UptimeVal.Hours)H:"; }
($true) { $Uptime += "$($UptimeVal.Minutes)M:$($UptimeVal.Seconds)S"; $DataHashTable.Add('Uptime', $Uptime); }
}
########################################################################################################################################################################################################
# Software
########################################################################################################################################################################################################
#WriteLog -Log "Gathering Software Information...";
$Apps = @();
$32BitPath = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*";
$64BitPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*";
$Apps += Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName,DisplayVersion;
$Apps += Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName,DisplayVersion;
$UserDefinedInstallations = @{
Name = 'DisplayName';
Expression = {
If ($_.DisplayName -NotLike "*(User)*") { "$($_.DisplayName) (User)"; }
Else { $_.DisplayName -replace "\(USER\)","(User)" }
}
}
$Apps += Get-ItemProperty "Registry::\HKEY_CURRENT_USER\$32BitPath" | Select-Object $UserDefinedInstallations,DisplayVersion;
$Apps += Get-ItemProperty "Registry::\HKEY_CURRENT_USER\$64BitPath" | Select-Object $UserDefinedInstallations,DisplayVersion;
$AllProfiles = Get-CimInstance Win32_UserProfile | Select-Object LocalPath, SID, Loaded, Special | Where-Object { $_.SID -Like "S-1-5-21-*" };
$MountedProfiles = $AllProfiles | Where-Object { $_.Loaded -eq $true; }
$UnmountedProfiles = $AllProfiles | Where-Object { $_.Loaded -eq $false; }
$MountedProfiles | ForEach-Object {
$Apps += Get-ItemProperty -Path "Registry::\HKEY_USERS\$($_.SID)\$($32BitPath)" | Select-Object $UserDefinedInstallations,DisplayVersion;
$Apps += Get-ItemProperty -Path "Registry::\HKEY_USERS\$($_.SID)\$($64BitPath)" | Select-Object $UserDefinedInstallations,DisplayVersion;
}