-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlueWindowsTriage.ps1
730 lines (652 loc) · 25.7 KB
/
BlueWindowsTriage.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
# Parameterize the output directory and log file path
param(
[string]$outputDir = "C:\\IncidentResponse\\$(Get-Date -Format 'yyyyMMdd_HHmmss')"
)
# Ensure the script is running with administrative privileges
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Error "Please run this script as an Administrator."
exit
}
# Record the start time
$scriptStartTime = Get-Date
# Create the output directory
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
# Initialize the log file
$logFile = "$outputDir\\script_log.txt"
Start-Transcript -Path $logFile -Append
# Initialize a mutex for synchronized logging
$logMutex = New-Object System.Threading.Mutex($false, "LogMutex")
$logMutex2 = New-Object System.Threading.Mutex($false, "LogMutex2")
# Global error logging function with batch processing to reduce call depth
function Write-Output-error {
param (
[string] $Message,
[string] $LogFile = "$outputDir\\error_log.txt"
)
# Collect errors in a list and log them periodically to avoid frequent I/O operations
if (-not $global:errorList) {
$global:errorList = @()
}
$global:errorList += "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ERROR: $Message"
if ($global:errorList.Count -gt 100) {
$logMutex.WaitOne() | Out-Null
try {
$global:errorList | Add-Content -Path $LogFile
$global:errorList.Clear()
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
}
function Write-Output-log {
param (
[string] $Message,
[string] $LogFile = "$outputDir\\error_log.txt"
)
# Collect errors in a list and log them periodically to avoid frequent I/O operations
if (-not $global:errorList) {
$global:errorList = @()
}
$global:errorList += "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ERROR: $Message"
if ($global:errorList.Count -gt 100) {
$logMutex2.WaitOne() | Out-Null
try {
$global:errorList | Add-Content -Path $LogFile
$global:errorList.Clear()
} finally {
$logMutex2.ReleaseMutex() | Out-Null
}
}
}
# Ensure any remaining errors are logged at the end of the script
function Clear-ErrorLog {
if ($global:errorList -and $global:errorList.Count -gt 0) {
$logMutex.WaitOne() | Out-Null
try {
$global:errorList | Add-Content -Path "$outputDir\\error_log.txt"
$global:errorList.Clear()
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
}
# Ensure any remaining errors are logged at the end of the script
function Clear-Log {
if ($global:errorList -and $global:errorList.Count -gt 0) {
$logMutex2.WaitOne() | Out-Null
try {
$global:errorList | Add-Content -Path "$outputDir\\error_log.txt"
$global:errorList.Clear()
} finally {
$logMutex2.ReleaseMutex() | Out-Null
}
}
}
# Function to calculate file hash with error handling and no recursion
function Get-FileHashSafely {
param(
[string]$FilePath,
[string]$Algorithm = 'SHA256'
)
try {
$hash = Get-FileHash -Path $FilePath -Algorithm $Algorithm -ErrorAction SilentlyContinue
return $hash.Hash
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error calculating hash for file: $FilePath - $_"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
return $null
}
}
function Export-RegistryKey {
param (
[string]$keyPath,
[string]$outputDir
)
$logMutex2.WaitOne() | Out-Null
try {
Write-Output "Exporting registry key: $keyPath" | Add-Content -Path "$outputDir\\script_log.txt"
} finally {
$logMutex2.ReleaseMutex() | Out-Null
}
try {
REG EXPORT $keyPath "$outputDir\\$(($keyPath -replace '\\', '_')).reg" /y
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output "Failed to export registry key: $keyPath. Error: $_" | Add-Content -Path "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
}
# Core Parallel Processing
$jobs = @()
# Collect system information
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$systemInfo = @{
"Hostname" = $env:COMPUTERNAME
"OS Version" = (Get-WmiObject -Class Win32_OperatingSystem).Caption
"Uptime" = (Get-Date) - (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
"Installed Software" = Get-WmiObject -Class Win32_Product | Select-Object Name, Version, InstallDate
# "Running Processes" = Get-Process | Select-Object Name, ID, Path, @{Name="User";Expression={$_.GetOwner().User}}
"Running Processes" = Get-Process | Select-Object Name, ID, Path, @{Name="User";Expression={$_.GetOwner().User}}, @{Name="ExecutablePath";Expression={$_.Path}}
"Network Configuration"= Get-NetIPConfiguration
}
$systemInfo | ConvertTo-Json | Out-File -FilePath "$outputDir\SystemInfo.json"
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting system information - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect startup items
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$startupItems = Get-CimInstance -ClassName Win32_StartupCommand | Select-Object -Property Command, Description, User, Location, Name
$startupItems | ConvertTo-Json | Out-File -FilePath "$outputDir\StartupItems.json"
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting startup items - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect information about local users and groups
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$userInfo = @{
"Local Users" = Get-LocalUser | Select-Object Name, Enabled, LastLogon
"User Groups" = Get-LocalGroup | Select-Object Name, SID
"Recent User Accounts"= Get-LocalUser | Where-Object {$_.CreateDate -ge (Get-Date).AddDays(-7)} | Select-Object Name, CreateDate
}
$userInfo | ConvertTo-Json | Out-File -FilePath "$outputDir\UserInfo.json"
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting user and group information - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect event logs in parallel
# Collect application logs
$jobs += Start-Job -ScriptBlock {
param($outputDir)
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
$tempEvtxPath = "$outputDir\Application_$(Get-Date -Format 'yyyyMMdd_HHmmss').evtx"
try {
$events = Get-WinEvent -LogName Application -MaxEvents 1500
$events | Export-Clixml -Path $tempEvtxPath
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output "Failed to collect Application event logs: $_" | Add-Content -Path "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect security logs
$jobs += Start-Job -ScriptBlock {
param($outputDir)
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
$tempEvtxPath = "$outputDir\Security_$(Get-Date -Format 'yyyyMMdd_HHmmss').evtx"
try {
$events = Get-WinEvent -LogName Security -MaxEvents 1500
$events | Export-Clixml -Path $tempEvtxPath
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output "Failed to collect Security event logs: $_" | Add-Content -Path "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect system logs
$jobs += Start-Job -ScriptBlock {
param($outputDir)
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
$tempEvtxPath = "$outputDir\System__$(Get-Date -Format 'yyyyMMdd_HHmmss').evtx"
try {
$events = Get-WinEvent -LogName System -MaxEvents 1500
$events | Export-Clixml -Path $tempEvtxPath
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output "Failed to collect System event logs: $_" | Add-Content -Path "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect current network connections
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$networkConnections = Get-NetTCPConnection | Select-Object State, LocalAddress, LocalPort, RemoteAddress, RemotePort, OwningProcess
$networkConnections | Export-Csv -Path "$outputDir\\NetworkConnections.csv" -NoTypeInformation
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting network connections - $_"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect registry startup items
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
$i = 1
try {
$registryKeys = @(
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
)
foreach ($key in $registryKeys) {
$keyName = $key.Split("\")[-1]
$keyValues = Get-ItemProperty -Path $key -ErrorAction SilentlyContinue
$keyValues | ConvertTo-Json | Out-File -FilePath "$outputDir\Registry_$keyName$1.json"
$i++
}
} catch {
$i++
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting registry data - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Export Shimcache data
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$shimcacheFile = "$outputDir\Shimcache.reg"
& reg export "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\AppCompatCache" $shimcacheFile /y
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Shimcache data - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect recent files from critical directories
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$criticalDirs = @("C:\Windows\System32", "C:\Windows\SysWOW64", "C:\Users\Public")
foreach ($dir in $criticalDirs) {
$recentFiles = Get-ChildItem -Path $dir -Recurse -File -ErrorAction Ignore | Where-Object {$_.LastWriteTime -ge (Get-Date).AddHours(-24) -and $_.Extension -ne ".evtx"}
$recentFiles | Select-Object FullName, LastWriteTime, Length, @{Name="Hash"; Expression={(Get-FileHash -Path $_.FullName).Hash}} | Export-Csv -Path "$outputDir\RecentFiles_$($dir.Replace(':', '').Replace('\', '_')).csv" -NoTypeInformation -ErrorAction Ignore
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting file system data - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect cookies from browsers for further analysis
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$cookiePaths = @(
"C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cookies",
"C:\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles\*\cookies.sqlite",
"C:\Users\*\AppData\Local\Microsoft\Edge\User Data\Default\Cookies"
)
foreach ($path in $cookiePaths) {
Get-ChildItem -Path $path -ErrorAction SilentlyContinue | Copy-Item -Destination $using:outputDir -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting browser cookies - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Collect scheduled tasks information
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$scheduledTasks = Get-ScheduledTask | Select-Object TaskName, TaskPath, State, LastRunTime, NextRunTime, Actions
$scheduledTasks | ConvertTo-Json | Out-File -FilePath "$outputDir\ScheduledTasks.json"
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting scheduled tasks - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Gather detailed information about services, including their status and configs
$jobs += Start-Job -ScriptBlock {
param($outputDir)
# Initialize a mutex for synchronized logging
$logMutex = [System.Threading.Mutex]::OpenExisting("LogMutex")
try {
$servicesInfo = Get-Service | Select-Object Name, DisplayName, Status, StartType, @{Name="Path";Expression={(Get-WmiObject -Class Win32_Service -Filter "Name='$($_.Name)'").PathName}}
$servicesInfo | ConvertTo-Json | Out-File -FilePath "$outputDir\ServicesInfo.json"
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting service information - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
} -ArgumentList $outputDir
# Wait for all jobs to complete
$jobs | ForEach-Object { $_ | Wait-Job | Receive-Job }
$jobs | Remove-Job
# Firefox Extension Collection
try {
$firefoxExtensionsPath = "C:\\Users\\*\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\*.default\\extensions"
$firefoxExtensions = Get-ChildItem -Path $firefoxExtensionsPath -Recurse -Directory -ErrorAction SilentlyContinue
$firefoxExtensions | ForEach-Object {
$manifestPath = "$($_.FullName)\\manifest.json"
if (Test-Path -Path $manifestPath) {
$extensionInfo = Get-Content -Path $manifestPath -Raw | ConvertFrom-Json
[PSCustomObject]@{
Id = $_.Name
Name = $extensionInfo.name
Version = $extensionInfo.version
Description = $extensionInfo.description
}
}
} | ForEach-Object {
$_ | Out-File -FilePath "$outputDir\\FirefoxExtensions.txt" -Append -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Firefox extensions - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Google Chrome Extension Collection
try {
$chromeExtensionsPath = "C:\\Users\\*\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions"
$chromeExtensions = Get-ChildItem -Path $chromeExtensionsPath -Recurse -Directory -ErrorAction SilentlyContinue
$chromeExtensions | ForEach-Object {
$manifestPath = "$($_.FullName)\\manifest.json"
if (Test-Path -Path $manifestPath) {
$extensionInfo = Get-Content -Path $manifestPath -Raw | ConvertFrom-Json
[PSCustomObject]@{
Id = $_.Name
Name = $extensionInfo.name
Version = $extensionInfo.version
Description = $extensionInfo.description
} | Out-File -FilePath "$outputDir\\ChromeExtensions.txt" -Append -Force
}
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Google Chrome extensions - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Chrome History Collection
try {
$chromeHistoryPath = "C:\\Users\\*\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History"
$chromeHistoryFiles = Get-ChildItem -Path $chromeHistoryPath -ErrorAction SilentlyContinue
$chromeHistoryFiles | ForEach-Object {
Copy-Item -Path $_.FullName -Destination "$outputDir\\ChromeHistory" -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Chrome history - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Firefox History Collection
try {
$firefoxHistoryPath = "C:\\Users\\*\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\*.default\\places.sqlite"
$firefoxHistoryFiles = Get-ChildItem -Path $firefoxHistoryPath -ErrorAction SilentlyContinue
$firefoxHistoryFiles | ForEach-Object {
Copy-Item -Path $_.FullName -Destination "$outputDir\\FirefoxHistory" -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Firefox history - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Microsoft Edge History Collection
try {
$edgeHistoryPath = "C:\\Users\\*\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\History"
$edgeHistoryFiles = Get-ChildItem -Path $edgeHistoryPath -ErrorAction SilentlyContinue
$edgeHistoryFiles | ForEach-Object {
Copy-Item -Path $_.FullName -Destination "$outputDir\\EdgeHistory.sqlite" -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Microsoft Edge history - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Search for Password Files
try {
$passwordFiles = Get-ChildItem -Path "C:\\Users\\*\\Documents\\*password*" -Recurse -ErrorAction SilentlyContinue
$passwordFiles | ForEach-Object {
Copy-Item -Path $_.FullName -Destination "$outputDir\\PasswordFiles" -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error searching for password files - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# User PowerShell History Collection
try {
$powershellHistoryPath = "C:\\Users\\*\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt"
$powershellHistoryFiles = Get-ChildItem -Path $powershellHistoryPath -ErrorAction SilentlyContinue
$powershellHistoryFiles | ForEach-Object {
$destinationPath = "$outputDir\\$($_.Directory.Name)"
New-Item -ItemType Directory -Path $destinationPath -Force | Out-Null
Copy-Item -Path $_.FullName -Destination $destinationPath -Force
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting PowerShell history - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Prefetch Files Collection
try {
# Create a subdirectory for prefetch files
$prefetchDir = "$outputDir\\PreFetch"
New-Item -ItemType Directory -Path $prefetchDir -Force | Out-Null
# Collect prefetch files
$prefetchFiles = Get-ChildItem -Path "C:\\Windows\\Prefetch" -ErrorAction SilentlyContinue
$prefetchFiles | Copy-Item -Destination $prefetchDir -Force
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting prefetch files - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Jump Lists Collection
try {
$jumpListFiles = Get-ChildItem -Path "C:\\Users\\*\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\AutomaticDestinations" -ErrorAction SilentlyContinue
$jumpListFiles | Copy-Item -Destination "$outputDir\\JumpLists" -Force
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting jump list files - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Windows Timeline Collection
try {
$timelineRegistry = "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ActivityDataModel"
# $timelineRegistryFile = "$outputDir\\Timeline.reg"
Export-RegistryKey -keyPath $timelineRegistry -outputDir $outputDir
$timelineFiles = Get-ChildItem -Path "C:\\Users\\*\\AppData\\Local\\ConnectedDevicesPlatform\\*\\ActivitiesCache.db" -ErrorAction SilentlyContinue
$timelineFiles | Copy-Item -Destination "$outputDir\\WindowsTimeline" -Force
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error collecting Windows Timeline data - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Hashing of Collected Files
try {
$collectedFiles = Get-ChildItem -Path $outputDir -File -Recurse
foreach ($file in $collectedFiles) {
$hash = Get-FileHashSafely -FilePath $file.FullName
if ($hash) {
$logMutex.WaitOne() | Out-Null
try {
Add-Content -Path "$outputDir\\Hashes.csv" -Value "$($file.FullName),$hash"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
}
} catch {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Error calculating hashes for collected files - $_" "$outputDir\\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Define the current working directory and the parent directory
$parentDirectory = Split-Path -Path $outputDir -Parent
$tempFolderName = "Temp$(Get-Date -Format 'yyyyMMdd_HHmmss')"
$tempFolderPath = "$parentDirectory\$tempFolderName"
New-Item -ItemType Directory -Path $tempFolderPath -Force
# Copy all files and folders recursively to the temporary folder while maintaining the directory structure
Get-ChildItem -Path $outputDir -Recurse | ForEach-Object {
if ($_.FullName -ne $tempFolderPath) {
$destination = Join-Path -Path $tempFolderPath -ChildPath $_.FullName.Substring($outputDir.Length-1)
if ($_.PSIsContainer) {
$logMutex.WaitOne() | Out-Null
try {
if ($_.FullName -ne $tempFolderPath -and $_.Name -ne $tempFolderName -and !(Test-Path $destination)) {
New-Item -ItemType Directory -Path $destination -Force
}
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
} else {
$logMutex.WaitOne() | Out-Null
try {
if ($_.DirectoryName -ne $tempFolderPath -and !(Test-Path $destination)) {
Copy-Item -Path $_.FullName -Destination $destination -Force
}
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
}
}
# Compress the temporary folder into a zip file in the output directory
$zipFileName = "IR-$(Get-Date -Format 'yyyyMMdd_HHmmss').zip"
$zipFilePath = "$parentDirectory\$zipFileName"
$zipParams = @{
path = $tempFolderPath
destinationPath = $zipFilePath
CompressionLevel = "Optimal"
}
Compress-Archive @zipParams
# Check if the zip file was created successfully
if (Test-Path $zipFilePath) {
# Delete the temporary folder
Remove-Item -Recurse -Force -Path $tempFolderPath
wait-event -timeout 3
$logMutex2.WaitOne() | Out-Null
try {
Write-Output "Backup created successfully: $zipFilePath" | Add-Content -Path "$outputDir\script_log.txt"
} finally {
$logMutex2.ReleaseMutex() | Out-Null
}
} else {
$logMutex.WaitOne() | Out-Null
try {
Write-Output-error "Zip file was not created. - $_" "$outputDir\error_log.txt"
} finally {
$logMutex.ReleaseMutex() | Out-Null
}
}
# Stop logging
Stop-Transcript | Out-Null
# Calculate and log total script execution time in a readable format
$scriptEndTime = Get-Date
$executionTime = $scriptEndTime - $scriptStartTime
# Translate execution time to a readable format
$days = $executionTime.Days
$hours = $executionTime.Hours
$minutes = $executionTime.Minutes
$seconds = $executionTime.Seconds
$readableExecutionTime = "$days days, $hours hours, $minutes minutes, $seconds seconds"
$logMutex2.WaitOne() | Out-Null
try {
Write-Output "Total script execution time: $readableExecutionTime" | Add-Content -Path "$outputDir\script_log.txt"
} finally {
$logMutex2.ReleaseMutex() | Out-Null
}
Clear-ErrorLog