-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitlockerRecoveryTools.psm1
More file actions
1107 lines (901 loc) · 35.8 KB
/
BitlockerRecoveryTools.psm1
File metadata and controls
1107 lines (901 loc) · 35.8 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
<#
.SYNOPSIS
Generates a BitLocker status and recovery key compliance report for Active Directory computers
using parallel processing.
.DESCRIPTION
Invoke-BitlockerTool queries domain-joined computers and collects:
• WinRM connectivity status
• BitLocker protection state
• Encryption percentage
• TPM presence and readiness
• Active Directory recovery key information
Optional remediation capabilities include:
• Automatically enabling BitLocker on eligible devices
• Backing up missing recovery keys to Active Directory
• Removing duplicate recovery password protectors
• Performing AD-only audits (no endpoint contact required)
Results are returned to the pipeline and exported to CSV.
This cmdlet uses CmdletBinding with SupportsShouldProcess and supports
-WhatIf and -Confirm for safe remediation execution.
Parallel execution is optimized for PowerShell 7+ using ForEach-Object -Parallel.
.INPUTS
None. Computer names are retrieved from Active Directory or a provided list.
.PARAMETER Filter
Active Directory filter string in standard PowerShell AD syntax.
This parameter is passed directly to Get-ADComputer -Filter.
Examples:
"Name -like 'LT-*'"
"Enabled -eq 'True'"
"OperatingSystem -notlike '*Server*'"
"Name -like 'LAB-*' -and Enabled -eq 'True'"
Default: *
NOTE:
This is NOT LDAP filter syntax.
.PARAMETER ComputerList
Path to a text file containing one computer name per line.
Lines beginning with # are ignored.
Useful for queue-based processing or retry batches.
.PARAMETER OutputPath
Path to the CSV report file.
Default: .\BitLocker_Report.csv
.PARAMETER Mode
Controls CSV export behavior.
Append – Adds to existing file
Overwrite – Replaces existing file
Default: Append
.PARAMETER ThrottleLimit
Maximum number of parallel threads when running under PowerShell 7+.
Default: 20
.PARAMETER IncludeRecoveryKey
Includes the most recent BitLocker recovery password stored in AD
in the exported report.
WARNING:
Recovery passwords are exported in plaintext.
.PARAMETER ADOnly
Performs an Active Directory–only audit of recovery key presence.
Skips WinRM connectivity and endpoint inspection.
.PARAMETER AutoEnableBitLocker
Automatically enables BitLocker on eligible machines where:
• BitLocker is not already enabled
• TPM is present
• TPM is ready
• No existing Machine RecoveryPassword protector exists
Supports -WhatIf and -Confirm.
.PARAMETER CleanupProtectors
Removes older duplicate recovery password protectors,
keeping only the newest protector.
.PARAMETER ContactedOnly
Includes only devices that are currently online in the CSV export.
.PARAMETER Confirm
Prompts for confirmation before performing remediation actions such as
enabling BitLocker or modifying recovery key protectors.
.EXAMPLE
Invoke-BitlockerTool
Runs against all domain computers (Filter defaults to *)
and exports a BitLocker compliance report.
.EXAMPLE
Invoke-BitlockerTool -Filter "Name -like 'LT-*'"
Reports on all laptop devices.
.EXAMPLE
Invoke-BitlockerTool -ComputerList .\queue.txt
Processes only machines listed in queue.txt
and attempts to escrow missing recovery keys.
.EXAMPLE
Invoke-BitlockerTool -ADOnly -IncludeRecoveryKey
Performs an AD-only recovery key audit without contacting endpoints.
.EXAMPLE
Invoke-BitlockerTool -Filter "Name -like 'LT-*'" ` -AutoEnableBitLocker`
-CleanupProtectors ` -IncludeRecoveryKey`
-Mode Overwrite `
-Confirm:$false
Full remediation mode:
• Enables BitLocker where eligible
• Removes duplicate protectors
• Includes recovery passwords
• Overwrites existing report
.OUTPUTS
PSCustomObject
Properties:
• Timestamp
• Computer
• Online
• WinRM
• Reported
• Volume
• Protected
• Percent
• MachineKeyCount
• ADKeyCount
• ADVerified
• ADRecoveryKeyID
• ADRecoveryKeyPassword
• LocalKeySource
• RecoveryKeyID
• RecoveryPassword
• TPMPresent
• TPMReady
• CanEnableBitLocker
• ActivatedBitlocker
• Error
.NOTES
Author: Bill Galway
Module: BitLockerTools
Version: 1.0
Requires:
• ActiveDirectory module
• BitLocker cmdlets
• WinRM enabled on target systems
• PowerShell 7+ Required
Supports:
• -WhatIf
• -Confirm
• Parallel execution with ForEach-Object -Parallel
• Safe CSV export
.LINK
https://learn.microsoft.com/en-us/powershell/module/bitlocker/
#>
function Invoke-BitlockerTool {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(ParameterSetName="AD")]
[string]$Filter = "*",
[Parameter(ParameterSetName="File")]
[string]$ComputerList,
[string]$OutputPath = ".\BitLocker_Report.csv",
[ValidateSet("Append","Overwrite")]
[string]$Mode = "Append",
[int]$ThrottleLimit = 20,
[switch]$ContactedOnly,
[switch]$IncludeRecoveryKey,
[switch]$ADOnly,
[switch]$AutoEnableBitLocker,
[switch]$CleanupProtectors
)
# --------------------------------------------------
# Build Computer List
# --------------------------------------------------
if ($PSCmdlet.ParameterSetName -eq "File") {
$Computers = Get-Content $ComputerList |
ForEach-Object { $_.Trim() } |
Where-Object { $_ -and -not $_.StartsWith("#") }
}
else {
$Computers = Get-ADComputer -Filter $Filter |
Select-Object -ExpandProperty Name
}
if (-not $Computers) {
Write-Log "No computers found to process."
return
}
Write-Log "Starting parallel BitLocker processing for $($Computers.Count) computers."
# --------------------------------------------------
# Parallel Processing
# --------------------------------------------------
$WhatIfFlag = $WhatIfPreference
$Results = $Computers | ForEach-Object -Parallel {
Import-Module C:\bat\BitlockerRecoveryTools\BitlockerRecoveryTools -Force
$ComputerName = $_
$IncludeKey = $using:IncludeRecoveryKey
$ADOnlyFlag = $using:ADOnly
$AutoEnable = $using:AutoEnableBitLocker
$CleanupFlag = $using:CleanupProtectors
$ContactedOnly = $using:ContactedOnly
$IsWhatIf = $using:WhatIfFlag
try {
# ----------------------------
# AD Only Mode
# ----------------------------
if ($ADOnlyFlag) {
$ADKeys = Get-ADBitLockerRecoveryKeys -ComputerName $ComputerName
$ADKeyCount = if ($ADKeys) { $ADKeys.Count } else { 0 }
return [PSCustomObject]@{
Timestamp = Get-Date
Computer = $ComputerName
Online = $false
WinRM = $false
Reported = $false
Volume = "C:"
Protected = $false
Percent = $null
MachineKeyCount = $null
ADKeyCount = $ADKeyCount
ADVerified = $false
ADRecoveryKeyID = if ($ADKeys) { $ADKeys.ADRecoveryKeyID } else { @() }
ADRecoveryKeyPassword = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
RecoveryKeyID = $null
RecoveryPassword = $null
TPMPresent = $false
TPMReady = $false
CanEnableBitLocker = $false
}
}
# ----------------------------
# Connectivity Test
# ----------------------------
$conn = Test-ComputerConnectivity -ComputerName $ComputerName
if (-not $conn.Online) { throw "Offline: $($conn.Reason)" }
if (-not $conn.WinRM) { throw "WinRM unavailable: $($conn.Reason)" }
# ----------------------------
# Remote BitLocker Snapshot
# ----------------------------
$status = Get-BitLockerStatus -ComputerName $ComputerName
#$status | Get-Member
# ----------------------------
# AD Recovery Keys
# ----------------------------
$ADKeys = @(Get-ADBitLockerRecoveryKeys -ComputerName $ComputerName)
$status.ADRecoveryKeyID = if ($ADKeys) { $ADKeys.ADRecoveryKeyID } else { @() }
$status.ADRecoveryKeyPassword = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
$ADPasswords = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
$ADKeyCount = $ADPasswords.Count
# Determine BitLocker Enable Eligibility
$keyInfo = Get-CVolumeRecoveryKeyCount -ComputerName $ComputerName
$MachineKeyCount = if ($keyInfo) { $keyInfo.MachineKeyCount } else { 0 }
$CanEnable = (
$status.Protected.ToString() -eq "Off" -and
$status.TpmPresent -and
$status.TpmReady -and
$MachineKeyCount -eq 0
)
$CanEnable = ($status.Protected.ToString() -eq "Off" -and $MachineKeyCount -eq 0)
# ----------------------------
# Optional Auto-Enable
# ----------------------------
$EnableBDEResult = $null
if ($AutoEnable -and $CanEnable) {
if ($IsWhatIf) {
Write-Log "WhatIf: Would enable BitLocker on $ComputerName" -ComputerName $ComputerName -Level "INFO"
}
else {
$EnableBDEResult = Enable-BitLockerRemote -ComputerName $ComputerName
if ($EnableBDEResult -and $EnableBDEResult.ProtectionStatus -ne "Off") {
Start-Sleep -Seconds 5
}
}
}
# ----------------------------
# Remove Password Protectors Keep Newest
# ----------------------------
if ($CleanupFlag) {
if (-not $IsWhatIf) {
Remove-ExtraBitLockerProtectors -ComputerName $ComputerName -IsWhatIf $IsWhatIf
}
else {
Write-Log "WhatIf: Would remove extra BitLocker protectors" -ComputerName $ComputerName
}
}
#------------------------------------------------------
# Backup local recovery key if not escrowed with AD
#------------------------------------------------------
$backup = Backup-BitLocker -Status $status -ADPasswords $ADPasswords -IsWhatIf $IsWhatIf
#--------------------------
# Backup local Recovery Key
#--------------------------
if ($EnableBDEResult) {
Write-Log "Local Recovery Keys Backup Attempted..Confirming" -ComputerName $ComputerName
$status = Get-BitLockerStatus -ComputerName $ComputerName
if (-not $status) { throw "Failed to retrieve BitLocker snapshot" }
$ADKeys = @(Get-ADBitLockerRecoveryKeys -ComputerName $ComputerName)
$status.Protected = $EnableBDEResult.ProtectionStatus
$status.ActivatedBitlocker = $EnableBDEResult.ActivatedBitlocker
$status.ADRecoveryKeyID = if ($ADKeys) { $ADKeys.ADRecoveryKeyID } else { @() }
$status.ADRecoveryKeyPassword = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
$ADPasswords = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
$ADKeyCount = $ADPasswords.Count
$backup = Backup-BitLocker -Status $status -ADPasswords $ADPasswords -IsWhatIf $IsWhatIf
}
#-----------------------------------------
#Confirme the local key was escrowed to AD
#-----------------------------------------
if ($backup.AttemptBackup) {
Write-Log "Backup BitLocker key attempted. Confirming Recovery Key Escrowed..." -ComputerName $ComputerName
$ADKeys = @(Get-ADBitLockerRecoveryKeys -ComputerName $ComputerName)
$status.ADRecoveryKeyID = if ($ADKeys) { $ADKeys.ADRecoveryKeyID } else { @() }
$status.ADRecoveryKeyPassword = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
$ADPasswords = if ($ADKeys) { $ADKeys.ADRecoveryPassword } else { @() }
$ADKeyCount = $ADPasswords.Count
$backup = Backup-BitLocker -Status $status -ADPasswords $ADPasswords -IsWhatIf $IsWhatIf
}
# ----------------------------
# Success Object
# ----------------------------
[PSCustomObject]@{
Timestamp = Get-Date
Computer = $ComputerName
Online = if ($conn) { $conn.Online } else { $false }
WinRM = if ($conn) { $conn.WinRM } else { $false }
Reported = $true
Volume = "C:"
Protected = $status.Protected
Percent = $status.Percent
MachineKeyCount = $MachineKeyCount
ADKeyCount = $ADKeyCount
ADVerified = $backup.ADVerified
ADRecoveryKeyID = $status.ADRecoveryKeyID
ADRecoveryKeyPassword = if ($IncludeKey) { $status.ADRecoveryKeyPassword }
LocalKeySource = $keyInfo.LocalKeySource
RecoveryKeyID = if ($status.RecoveryKeyID) {
[string]$status.RecoveryKeyID.Trim('{}')
} else {
$null
}
RecoveryPassword = if ($IncludeKey) { $status.RecoveryPassword }
TPMPresent = $status.TpmPresent
TPMReady = $status.TpmReady
CanEnableBitLocker = $CanEnable
ActivatedBitlocker = $status.ActivatedBitlocker
}
}
catch {
# ----------------------------
# Failure Object
# ----------------------------
Write-Log "ERROR: $($_.Exception.Message)" -Level "ERROR" -ComputerName $ComputerName
[PSCustomObject]@{
Timestamp = Get-Date
Computer = $ComputerName
Online = if ($conn) { $conn.Online } else { $false }
WinRM = if ($conn) { $conn.WinRM } else { $false }
Reported = $false
Volume = $null
Protected = $null
Percent = $null
MachineKeyCount = $null
ADKeyCount = $null
ADVerified = $false
ADRecoveryKeyID = $null
ADRecoveryKeyPassword = $null
LocalKeySource = $null
RecoveryKeyID = $null
RecoveryPassword = $null
TPMPresent = $false
TPMReady = $false
CanEnableBitLocker = $false
ActivatedBitlocker = $false
}
}
} -ThrottleLimit $ThrottleLimit
# --------------------------------------------------
# Track Unreachable Machines (ALWAYS from full results)
# --------------------------------------------------
$NotContactedPath = Join-Path (Split-Path $OutputPath) "NotContacted_Computers.txt"
if (-not (Test-Path $NotContactedPath)) {
New-Item -Path $NotContactedPath -ItemType File | Out-Null
}
$existing = Get-Content $NotContactedPath -ErrorAction SilentlyContinue
$newUnreachable = $Results |
Where-Object { $_.Online -eq $false } |
Select-Object -ExpandProperty Computer |
Where-Object { $_ -and ($existing -notcontains $_) } |
Sort-Object
if ($newUnreachable) {
$newUnreachable | Out-File -FilePath $NotContactedPath -Encoding UTF8 -Append
Write-Host "Added $($newUnreachable.Count) new unreachable computers." -ForegroundColor Yellow
}
else {
Write-Log "No new unreachable computers to add."
}
# --------------------------------------------------
# Comment out successfully contacted computers
# --------------------------------------------------
if ($PSCmdlet.ParameterSetName -eq "File") {
$successful = $Results |
Where-Object { $_.Online -eq $true } |
Select-Object -ExpandProperty Computer |
Sort-Object
if ($successful) {
$lines = Get-Content $ComputerList
$updated = foreach ($line in $lines) {
$trim = $line.Trim()
if ($trim -and ($successful -contains $trim) -and -not $trim.StartsWith("#")) {
"#$trim"
}
else {
$line
}
}
$updated | Set-Content -Path $ComputerList -Encoding UTF8
Write-Host "Commented out $($successful.Count) successfully contacted computers in $ComputerList." -ForegroundColor Cyan
}
else {
Write-Host "No successfully contacted computers to comment out." -ForegroundColor DarkGray
}
}
# --------------------------------------------------
# Export CSV - Apply -ContactedOnly filtering ONLY here
# --------------------------------------------------
$ExportResults = if ($ContactedOnly) {
$Results | Where-Object { $_.Online -eq $true }
}
else {
$Results
}
if ($ExportResults) {
Export-ResultsSafe -Results $ExportResults -Path $OutputPath -Mode $Mode
}
return $ExportResults
}
# ----------------------------
# Logging helper
# ----------------------------
function Write-Log {
param(
[string]$Message,
[string]$Level = "INFO",
[string]$ComputerName
)
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
if ($ComputerName) {
$line = "[$time][$Level][$ComputerName] $Message"
}
else {
$line = "[$time][$Level] $Message"
}
# Console output (not mutex-protected)
Write-Host $line
# File output (mutex-protected)
try {
$null = $script:LogMutex.WaitOne()
Add-Content -Path $script:LogPath -Value $line -Encoding UTF8
}
finally {
$script:LogMutex.ReleaseMutex() | Out-Null
}
}
function Test-ComputerConnectivity {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ComputerName
)
# Default result object
$result = [PSCustomObject]@{
ComputerName = $ComputerName
Online = $false
WinRM = $false
Reason = $null
}
try {
# Basic ICMP reachability
if (-not (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet -ErrorAction SilentlyContinue)) {
$result.Reason = "Ping failed"
return $result
}
$result.Online = $true
# WSMan test (remote PowerShell availability)
try {
Test-WSMan -ComputerName $ComputerName -ErrorAction Stop | Out-Null
$result.WinRM = $true
}
catch {
$result.Reason = "WinRM unavailable: $($_.Exception.Message)"
}
}
catch {
$result.Reason = "Unexpected error: $($_.Exception.Message)"
}
return $result
}
# ----------------------------
# Define the master template once
# ----------------------------
$BitLockerTemplate = [PSCustomObject]@{
Timestamp = Get-Date
Computer = $null
Online = $false
Reported = $false
Volume = "C:"
Protected = $false
Percent = 0
MachineKeyCount = 0
ADKeyCount = 0
ADVerified = $null
ADRecoveryKeyID = $null
ADRecoveryKeyPassword = $null
LocalKeySource = $null
RecoveryKeyID = $null
RecoveryPassword = $null
TPMPresent = $false
TPMReady = $false
CanEnableBitLocker = $null
ActivatedBitlocker = $false
Error = $null
}
# ----------------------------
# Optional helper to get a fresh copy of the template
# ----------------------------
function New-BitLockerResult {
param([string]$ComputerName)
$obj = $BitLockerTemplate.PSObject.Copy()
$obj.Computer = $ComputerName
return $obj
}
function Get-BitLockerStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ComputerName
)
# Start with fresh template
$result = New-BitLockerResult -ComputerName $ComputerName
try {
$snapshot = Invoke-Command -ComputerName $ComputerName -ErrorAction Stop -ScriptBlock {
param($template, $computer)
# Fresh copy in remote session
$remoteResult = $template.PSObject.Copy()
$remoteResult.Computer = $computer
$remoteResult.Online = $true
try {
# Attempt to get BitLocker volume
$vol = Get-BitLockerVolume -MountPoint 'C:' -ErrorAction Stop |
Select-Object -First 1
if (-not $vol) {
$remoteResult.Error = "BitLocker volume not found."
return $remoteResult
}
$remoteResult.Protected = $vol.ProtectionStatus
$remoteResult.Percent = $vol.EncryptionPercentage
# Recovery Password Protectors
$rp = @($vol.KeyProtector | Where-Object { $_.KeyProtectorType -eq 'RecoveryPassword' })
$remoteResult.MachineKeyCount = $rp.Count
if ($rp.Count -gt 0) {
$newest = $rp | Sort-Object CreationTime -Descending | Select-Object -First 1
$remoteResult.RecoveryKeyID = $newest.KeyProtectorId
$remoteResult.RecoveryPassword = $newest.RecoveryPassword
}
# TPM info
try {
$tpm = Get-Tpm -ErrorAction Stop
$remoteResult.TPMPresent = $true
$remoteResult.TPMReady = $tpm.TpmReady
}
catch {
# TPM absence is expected; do nothing
}
$remoteResult.Reported = $true
return $remoteResult
}
catch {
$remoteResult.Error = $_.Exception.Message
return $remoteResult
}
} -ArgumentList $BitLockerTemplate, $ComputerName
if ($snapshot.Count -eq 1) { $snapshot = $snapshot[0] }
$result = $snapshot
}
catch {
# Only triggers on true remoting failure
$result.Error = $_.Exception.Message
$result.Online = $false
}
return $result
}
# ----------------------------
# AD Recovery Key query
# ----------------------------
function Get-ADBitLockerRecoveryKeys {
param([string]$ComputerName)
try {
$Comp = Get-ADComputer -Identity $ComputerName -ErrorAction Stop
Write-Log "Found computer: $($Comp.DistinguishedName)" -ComputerName $ComputerName
$RecoveryObjects = Get-ADObject `
-Filter {objectClass -eq "msFVE-RecoveryInformation"} `
-SearchBase $Comp.DistinguishedName `
-Properties msFVE-RecoveryPassword `
-ErrorAction Stop
$KeyCount = ($RecoveryObjects | Measure-Object).Count
Write-Log "Found $KeyCount Escrowed AD BitLocker recovery key(s)" -ComputerName $ComputerName
return $RecoveryObjects | ForEach-Object {
[PSCustomObject]@{
Computer = $ComputerName
ADRecoveryKeyID = $_.ObjectGUID.ToString().Trim('{}')
ADRecoveryPassword = if ($_.PSObject.Properties['msFVE-RecoveryPassword']) {
$_.'msFVE-RecoveryPassword'.Trim()
} else { "" }
}
}
}
catch {
Write-Log "ERROR: Failed to get BitLocker keys - $($_.Exception.Message)" -ComputerName $ComputerName
return @()
}
}
function Enable-BitLockerRemote {
param(
[string]$ComputerName
)
Write-Log "Starting Enable BitLocker Remote" -ComputerName $ComputerName
try {
$result = Invoke-Command -ComputerName $ComputerName -ScriptBlock {
$mount = "C:"
$vol = Get-BitLockerVolume -MountPoint $mount -ErrorAction Stop | Select-Object -First 1
if ($null -eq $vol) { throw "Volume $mount not found" }
# Resume if suspended
if ($vol.VolumeStatus -eq "Suspended") {
Resume-BitLocker -MountPoint $mount -ErrorAction Stop
Start-Sleep 3
}
# Enable BitLocker if protection is off
if ($vol.ProtectionStatus -eq "Off") {
Enable-BitLocker -MountPoint $mount `
-EncryptionMethod XtsAes256 `
-RecoveryPasswordProtector `
-Confirm:$false -ErrorAction Stop | Out-Null
}
} -ErrorAction Stop | Select-Object -First 1
# Return a simple status object
$status = [PSCustomObject]@{
ProtectionStatus = "Off (Reboot Pending)"
ActivatedBitlocker = $true
}
Write-Log "BitLocker operation completed on $ComputerName" -ComputerName $ComputerName
return $status
}
catch {
$errorMsg = $_.Exception.Message
Write-Log "Failed to enable BitLocker on $ComputerName : $errorMsg" -Level ERROR -ComputerName $ComputerName
return $null
}
}
# ----------------------------
# Remove extra recovery protectors (keep newest)
# ----------------------------
function Remove-ExtraBitLockerProtectors {
param(
[string]$ComputerName,
[bool]$IsWhatIf
)
try {
Write-Log "Starting BitLocker protector cleanup..." -ComputerName $ComputerName
# Get volume and protectors remotely
$protectors = Invoke-Command -ComputerName $ComputerName -ScriptBlock {
Get-BitLockerVolume -MountPoint "C:" | Select-Object -First 1
}
if (-not $protectors) {
Write-Log "ERROR: Unable to retrieve BitLocker volume on $ComputerName" -Level ERROR -ComputerName $ComputerName
return
}
$passwords = @($protectors.KeyProtector | Where-Object { $_.KeyProtectorType -eq "RecoveryPassword" })
if ($passwords.Count -le 1) {
Write-Log "No duplicate protectors found" -ComputerName $ComputerName
return
}
# Keep only the newest
$keep = $passwords | Sort-Object CreationTime -Descending | Select-Object -First 1
Write-Log "Keeping newest protector $($keep.KeyProtectorId)" -ComputerName $ComputerName
# Prepare list of IDs to remove
$toRemove = $passwords | Where-Object { $_.KeyProtectorId -ne $keep.KeyProtectorId } | Select-Object -ExpandProperty KeyProtectorId
# Remove each protector one by one
foreach ($id in $toRemove) {
if ((-not $IsWhatIf)) {
Invoke-Command -ComputerName $ComputerName -ScriptBlock {
param($RemoveID)
Remove-BitLockerKeyProtector -MountPoint "C:" -KeyProtectorId $RemoveID -ErrorAction Stop
} -ArgumentList $id
Write-Log "Removed protector $id" -ComputerName $ComputerName
}
else {
Write-Log "WhatIf: Would remove protector $id" -ComputerName $ComputerName
}
}
Write-Log "BitLocker protector cleanup complete." -ComputerName $ComputerName
}
catch {
Write-Log "ERROR: Failed during cleanup: $($_.Exception.Message)" -Level ERROR -ComputerName $ComputerName
}
}
function Get-CVolumeRecoveryKeyCount {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ComputerName,
[switch]$Raw
)
# Retry settings
$maxRetries = 3
$retryDelay = 2
# Start with template
$result = New-BitLockerResult -ComputerName $ComputerName
$result.LocalKeySource = "None"
# ----------------------------
# 1️⃣ Preferred Method: Get-BitLockerStatus
# ----------------------------
try {
for ($i = 1; $i -le $maxRetries; $i++) {
$snapshot = Get-BitLockerStatus -ComputerName $ComputerName
if ($snapshot -and $snapshot.Reported) {
$result = $snapshot
$result.LocalKeySource = "BitLockerStatus"
if ($Raw) {
return $result.MachineKeyCount
}
return [PSCustomObject]@{
Computer = $result.Computer
Online = $result.Online
Reported = $result.Reported
MachineKeyCount = $result.MachineKeyCount
ProtectionStatus = $result.Protected
LocalKeySource = $result.LocalKeySource
Error = $result.Error
}
}
Start-Sleep -Seconds $retryDelay
}
}
catch {
$result.Error = $_.Exception.Message
}
# ----------------------------
# 2️⃣ Fallback: manage-bde
# ----------------------------
try {
$bdeCount = Invoke-Command -ComputerName $ComputerName -ErrorAction Stop -ScriptBlock {
try {
$output = manage-bde -protectors -get C: | Out-String
return ($output | Select-String "Numerical Password").Count
}
catch {
return -1
}
}
if ($bdeCount -ge 0) {
$result.Reported = $true
$result.LocalKeySource = "ManageBDE"
$result.MachineKeyCount = $bdeCount
if ($Raw) {
return $bdeCount
}
return [PSCustomObject]@{
Computer = $result.Computer
Online = $true
Reported = $true
MachineKeyCount = $bdeCount
ProtectionStatus = "Unknown"
LocalKeySource = "ManageBDE"
Error = $null
}
}
}
catch {
$result.Error = $_.Exception.Message
}
# ----------------------------
# 3️⃣ Final Failure Return
# ----------------------------
if ($Raw) {
return 0
}
return [PSCustomObject]@{
Computer = $ComputerName
Online = $false
Reported = $false
MachineKeyCount = 0
ProtectionStatus = "Unknown"
LocalKeySource = "Failed"
Error = $result.Error
}
}
# ----------------------------
# ----Backup Bitlocker--------
# ----------------------------
function Backup-BitLocker {
param(
[Parameter(Mandatory)]
[PSCustomObject]$Status,
[string[]]$ADPasswords,
[bool]$IsWhatIf
)
$AttemptBackup = $false
$ADVerified = $false
$LocalKey = $Status.RecoveryPassword
$RecoveryKeyID = if ($Status.RecoveryKeyID) { [string]$Status.RecoveryKeyID.Trim('{}') } else { $null }
if (-not $LocalKey) {
Write-Log "No valid RecoveryPassword protector found — skipping backup" -Level "WARN" -ComputerName $Status.Computer
return [PSCustomObject]@{
ADVerified = $false
RecoveryKeyID = $RecoveryKeyID
RecoveryPassword = $LocalKey
}
}
if (-not $ADPasswords) { $ADPasswords = @() }
$IsEscrowed = if ($ADPasswords.Count -gt 0) { $ADPasswords -contains $LocalKey } else { $false }
if (-not $IsEscrowed) {
$AttemptBackup = $true
Write-Log "Backing up BitLocker recovery key ID: $RecoveryKeyID" -ComputerName $Status.Computer
try {
if (-not $IsWhatIf) {
Invoke-Command -ComputerName $Status.Computer -ScriptBlock {
param($MP, $KPID)