-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileLabeler.ps1
More file actions
5663 lines (4901 loc) · 239 KB
/
FileLabeler.ps1
File metadata and controls
5663 lines (4901 loc) · 239 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
#Requires -Version 5.1
<#
.SYNOPSIS
Massemerking av filer - Påfør følsomhetsetiketter med datobevaring
.DESCRIPTION
GUI-applikasjon for massepåføring av Microsoft Purview følsomhetsetiketter til Office-dokumenter og PDF-er.
Bevarer opprinnelige fildatoer.
.NOTES
Krever: Microsoft Purview Information Protection-klient og PurviewInformationProtection-modul
#>
# ========================================
# CRITICAL: PowerShell Transcript
# ========================================
# Captures ALL output, errors, and warnings - even crashes that escape error handlers
$transcriptDir = Join-Path $env:USERPROFILE "Documents\FileLabeler_Logs"
if (-not (Test-Path $transcriptDir)) {
New-Item -Path $transcriptDir -ItemType Directory -Force | Out-Null
}
$transcriptPath = Join-Path $transcriptDir "TRANSCRIPT_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
Start-Transcript -Path $transcriptPath -Force | Out-Null
# Set output encoding to UTF-8
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
# Import necessary assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Enable visual styles
[System.Windows.Forms.Application]::EnableVisualStyles()
# ========================================
# GLOBAL ERROR HANDLER
# ========================================
# Trap ALL unhandled exceptions before they crash the application
trap {
$crashTimestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$crashLogDir = Join-Path $env:USERPROFILE "Documents\FileLabeler_Logs"
# Ensure log directory exists
if (-not (Test-Path $crashLogDir)) {
New-Item -Path $crashLogDir -ItemType Directory -Force | Out-Null
}
# Create detailed crash report
$crashInfo = @{
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
ExceptionMessage = $_.Exception.Message
ExceptionType = $_.Exception.GetType().FullName
StackTrace = if ($_.ScriptStackTrace) { $_.ScriptStackTrace } else { "No stack trace available" }
InvocationLine = if ($_.InvocationInfo) { $_.InvocationInfo.Line } else { "Unknown" }
InvocationPosition = if ($_.InvocationInfo) { $_.InvocationInfo.PositionMessage } else { "Unknown" }
CategoryInfo = $_.CategoryInfo.ToString()
FullyQualifiedErrorId = $_.FullyQualifiedErrorId
}
# Save as JSON for easy parsing
$crashLogPath = Join-Path $crashLogDir "CRASH_$crashTimestamp.json"
try {
$crashInfo | ConvertTo-Json -Depth 10 | Set-Content $crashLogPath -Encoding UTF8
} catch {
# Fallback to text if JSON fails
$crashLogPath = Join-Path $crashLogDir "CRASH_$crashTimestamp.txt"
$crashInfo | Out-String | Set-Content $crashLogPath
}
# Also write to regular log if available
if (Test-Path variable:script:logFilePath) {
try {
Add-Content -Path $script:logFilePath -Value "`n=== UNHANDLED EXCEPTION TRAPPED ===" -ErrorAction SilentlyContinue
Add-Content -Path $script:logFilePath -Value "[$($crashInfo.Timestamp)] [CRITICAL] $($crashInfo.ExceptionMessage)" -ErrorAction SilentlyContinue
Add-Content -Path $script:logFilePath -Value "Type: $($crashInfo.ExceptionType)" -ErrorAction SilentlyContinue
Add-Content -Path $script:logFilePath -Value "Stack: $($crashInfo.StackTrace)" -ErrorAction SilentlyContinue
} catch {}
}
# Show error dialog to user
$errorMsg = "KRITISK FEIL - Applikasjonen krasjet!`n`n"
$errorMsg += "Feil: $($_.Exception.Message)`n`n"
$errorMsg += "Type: $($_.Exception.GetType().Name)`n`n"
$errorMsg += "Detaljer lagret i:`n$crashLogPath`n`n"
$errorMsg += "Vennligst send denne filen til support."
[System.Windows.Forms.MessageBox]::Show(
$errorMsg,
"Kritisk feil",
[System.Windows.Forms.MessageBoxButtons]::OK,
[System.Windows.Forms.MessageBoxIcon]::Error
)
# Try to open crash log
try {
Start-Process notepad.exe -ArgumentList $crashLogPath -ErrorAction SilentlyContinue
} catch {}
# Continue execution instead of terminating
continue
}
# ========================================
# EARLY INITIALIZATION - LOG DIRECTORY
# ========================================
# Create log directory BEFORE anything else (needed for Write-Log)
$logDirectory = Join-Path $env:USERPROFILE "Documents\FileLabeler_Logs"
if (-not (Test-Path $logDirectory)) {
New-Item -Path $logDirectory -ItemType Directory -Force | Out-Null
}
$logFilePath = Join-Path $logDirectory "FileLabeler_Log_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
# ========================================
# HELPER FUNCTIONS (DEFINED EARLY FOR USE THROUGHOUT)
# ========================================
<#
.SYNOPSIS
Enhanced logging function with structured output and log levels
.DESCRIPTION
Writes log entries with severity levels, source information, and diagnostic context
.PARAMETER Message
The message to log
.PARAMETER Level
Log severity level: INFO, WARNING, ERROR, CRITICAL
.PARAMETER Source
Source of the log entry (function/operation name)
.PARAMETER Context
Additional context (e.g., file path, operation details)
.PARAMETER Exception
Exception object to include stack trace and details
#>
function Write-Log {
param(
[Parameter(Mandatory=$true)]
[string]$Message,
[Parameter(Mandatory=$false)]
[ValidateSet('INFO', 'WARNING', 'ERROR', 'CRITICAL')]
[string]$Level = 'INFO',
[Parameter(Mandatory=$false)]
[string]$Source = '',
[Parameter(Mandatory=$false)]
[hashtable]$Context = @{},
[Parameter(Mandatory=$false)]
[System.Management.Automation.ErrorRecord]$Exception = $null
)
try {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
# Build structured log entry
$logEntry = "[$timestamp] [$Level]"
if ($Source) {
$logEntry += " [$Source]"
}
$logEntry += " $Message"
# Add context if provided
if ($Context.Count -gt 0) {
$contextStr = ($Context.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join "; "
$logEntry += " | Context: $contextStr"
}
# Add exception details if provided
if ($Exception) {
$logEntry += "`n Exception: $($Exception.Exception.Message)"
$logEntry += "`n Type: $($Exception.Exception.GetType().FullName)"
# Include stack trace for ERROR and CRITICAL levels
if ($Level -in @('ERROR', 'CRITICAL') -and $Exception.ScriptStackTrace) {
$logEntry += "`n StackTrace: $($Exception.ScriptStackTrace)"
}
# Include inner exception if present
if ($Exception.Exception.InnerException) {
$logEntry += "`n InnerException: $($Exception.Exception.InnerException.Message)"
}
}
# Write to log file
Add-Content -Path $script:logFilePath -Value $logEntry -ErrorAction SilentlyContinue
# For CRITICAL errors, also write to Windows Event Log (if possible)
if ($Level -eq 'CRITICAL') {
try {
Write-EventLog -LogName Application -Source "FileLabeler" -EventId 1000 -EntryType Error -Message $Message -ErrorAction SilentlyContinue
} catch {
# Silently fail if event log not accessible
}
}
}
catch {
# Fallback: write minimal log entry if structured logging fails
try {
$fallbackEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] [ERROR] Logging failed: $($_.Exception.Message). Original message: $Message"
Add-Content -Path $script:logFilePath -Value $fallbackEntry -ErrorAction SilentlyContinue
}
catch {
# Ultimate fallback: do nothing to avoid infinite loops
}
}
}
<#
.SYNOPSIS
Get user-friendly error message for common error scenarios
.DESCRIPTION
Translates technical errors into actionable user messages
.PARAMETER Exception
The exception to translate
.OUTPUTS
Hashtable with UserMessage and TechnicalDetails
#>
function Get-FriendlyErrorMessage {
param(
[Parameter(Mandatory=$true)]
$Exception
)
$errorMessage = $Exception.Exception.Message
$errorType = $Exception.Exception.GetType().Name
# Common error patterns and user-friendly messages
$errorPatterns = @{
# File access errors
'UnauthorizedAccessException|Access.*denied' = @{
UserMessage = "Ingen tilgang til filen. Sjekk at du har nødvendige tillatelser."
Category = "FileAccess"
Suggestion = "Høyreklikk på filen, velg Egenskaper → Sikkerhet, og kontroller dine tillatelser."
}
'IOException.*process.*another' = @{
UserMessage = "Filen er i bruk av et annet program. Lukk filen og prøv igjen."
Category = "FileLocked"
Suggestion = "Lukk dokumentet i Word/Excel/PowerPoint og prøv på nytt."
}
'FileNotFoundException|Could not find.*file' = @{
UserMessage = "Filen ble ikke funnet. Den kan være flyttet eller slettet."
Category = "FileNotFound"
Suggestion = "Kontroller at filen fortsatt eksisterer på angitt plassering."
}
# Network errors
'IOException.*network' = @{
UserMessage = "Nettverksfeil. Kontroller nettverkstilkoblingen og prøv igjen."
Category = "Network"
Suggestion = "Sjekk nettverkstilkobling. Hvis filen er på en nettverksmappe, kontroller at du er koblet til nettverket."
}
'DirectoryNotFoundException' = @{
UserMessage = "Mappen ble ikke funnet. Kontroller at stien er korrekt."
Category = "DirectoryNotFound"
Suggestion = "Sjekk at mappen eksisterer og at stien er korrekt."
}
# AIP-specific errors
'Justification' = @{
UserMessage = "Begrunnelse kreves for å nedgradere følsomhetsetikett."
Category = "AIPJustification"
Suggestion = "Angi en gyldig begrunnelse for nedgraderingen."
}
'AdhocProtectionRequired|ad-hoc protection' = @{
UserMessage = "Valgt etikett krever beskyttelsesinnstillinger."
Category = "AIPProtection"
Suggestion = "Angi hvem som skal ha tilgang til filen og hvilke rettigheter de skal ha."
}
# General errors
'OutOfMemoryException' = @{
UserMessage = "Ikke nok minne tilgjengelig. Prøv å behandle færre filer om gangen."
Category = "Memory"
Suggestion = "Lukk andre programmer eller reduser antall filer som behandles samtidig."
}
'TimeoutException' = @{
UserMessage = "Operasjonen tok for lang tid og ble avbrutt."
Category = "Timeout"
Suggestion = "Prøv igjen med færre filer, eller sjekk nettverkshastigheten."
}
}
# Find matching pattern
foreach ($pattern in $errorPatterns.Keys) {
if ($errorMessage -match $pattern -or $errorType -match $pattern) {
return @{
UserMessage = $errorPatterns[$pattern].UserMessage
TechnicalDetails = $errorMessage
Category = $errorPatterns[$pattern].Category
Suggestion = $errorPatterns[$pattern].Suggestion
}
}
}
# Default fallback message
return @{
UserMessage = "En uventet feil oppstod under behandling."
TechnicalDetails = $errorMessage
Category = "Unknown"
Suggestion = "Se loggfil for mer informasjon. Prøv operasjonen på nytt, eller kontakt support hvis feilen vedvarer."
}
}
<#
.SYNOPSIS
Show error dialog with user-friendly message and recovery options
.DESCRIPTION
Displays error to user with actionable suggestions and optional log viewing
.PARAMETER ErrorInfo
Hashtable from Get-FriendlyErrorMessage
.PARAMETER ShowLogOption
Whether to show "View Log" button
#>
function Show-ErrorDialog {
param(
[Parameter(Mandatory=$true)]
[hashtable]$ErrorInfo,
[Parameter(Mandatory=$false)]
[bool]$ShowLogOption = $true,
[Parameter(Mandatory=$false)]
[string]$Title = "Feil"
)
# Build message
$message = $ErrorInfo.UserMessage
if ($ErrorInfo.Suggestion) {
$message += "`n`nForslag: $($ErrorInfo.Suggestion)"
}
if ($ErrorInfo.TechnicalDetails -and $ErrorInfo.TechnicalDetails.Length -lt 200) {
$message += "`n`nTeknisk detalj: $($ErrorInfo.TechnicalDetails)"
}
if ($ShowLogOption) {
$message += "`n`nKlikk 'Vis logg' for mer informasjon."
}
# Show dialog
$result = [System.Windows.Forms.MessageBox]::Show(
$message,
$Title,
[System.Windows.Forms.MessageBoxButtons]::OK,
[System.Windows.Forms.MessageBoxIcon]::Error
)
return $result
}
# ========================================
# MODULE VALIDATION
# ========================================
$moduleName = "PurviewInformationProtection"
if (-not (Get-Module -ListAvailable -Name $moduleName)) {
[System.Windows.Forms.MessageBox]::Show(
"ERROR: $moduleName module is not installed.`n`nPlease install the Microsoft Purview Information Protection client first.`n`nDownload from: https://www.microsoft.com/en-us/download/details.aspx?id=53018",
"Missing Required Module",
[System.Windows.Forms.MessageBoxButtons]::OK,
[System.Windows.Forms.MessageBoxIcon]::Error
)
exit 1
}
try {
Import-Module $moduleName -ErrorAction Stop
Write-Log -Message "$moduleName module imported successfully" -Level 'INFO' -Source 'ModuleValidation'
} catch {
Write-Log -Message "Failed to import $moduleName module" -Level 'CRITICAL' -Source 'ModuleValidation' -Exception $_
[System.Windows.Forms.MessageBox]::Show(
"ERROR: Failed to import $moduleName module.`n`nError: $_",
"Module Import Failed",
[System.Windows.Forms.MessageBoxButtons]::OK,
[System.Windows.Forms.MessageBoxIcon]::Error
)
exit 1
}
# ========================================
# GET AVAILABLE LABELS
# ========================================
$labels = @()
# Method 1: Try to get labels from Security & Compliance Center (if module is available)
$securityModules = @("ExchangeOnlineManagement", "Microsoft.Online.SharePoint.PowerShell")
$labelsRetrieved = $false
foreach ($secModule in $securityModules) {
if (Get-Module -ListAvailable -Name $secModule) {
try {
Import-Module $secModule -ErrorAction SilentlyContinue
$labels = Get-Label -ErrorAction SilentlyContinue
if ($labels -and $labels.Count -gt 0) {
$labelsRetrieved = $true
break
}
} catch {
# Continue to next method
}
}
}
# Method 2: If no labels retrieved, use predefined list or allow manual entry
if (-not $labelsRetrieved -or $labels.Count -eq 0) {
# Check if there's a labels configuration file
$labelsConfigPath = Join-Path $PSScriptRoot "labels_config.json"
if (Test-Path $labelsConfigPath) {
try {
$labelsJson = Get-Content $labelsConfigPath -Raw | ConvertFrom-Json
$labels = $labelsJson
} catch {
# Will use default labels below
}
}
# If still no labels, show a helpful message and provide default structure
if (-not $labels -or $labels.Count -eq 0) {
$result = [System.Windows.Forms.MessageBox]::Show(
"Could not automatically retrieve sensitivity labels.`n`nThis can happen if:`n- You're not connected to Security & Compliance Center`n- Labels need to be configured manually`n`nWould you like to:`nYES - Continue with manual label entry`nNO - Exit and configure labels first`n`nNote: You can create a 'labels_config.json' file in the script directory with your organization's labels.",
"Label Configuration Required",
[System.Windows.Forms.MessageBoxButtons]::YesNo,
[System.Windows.Forms.MessageBoxIcon]::Question
)
if ($result -eq 'No') {
exit 0
}
# Provide empty list for manual entry
$labels = @()
}
}
# ========================================
# GLOBAL VARIABLES & CONSTANTS
# ========================================
$selectedFiles = @()
$fileLabelCache = @{} # Cache for file label status to avoid repeated API calls
# Supported file extensions (centralized constant)
$script:SupportedExtensions = @('.docx', '.xlsx', '.pptx', '.doc', '.xls', '.ppt', '.pdf')
$script:SupportedExtensionPatterns = @('*.docx', '*.xlsx', '*.pptx', '*.doc', '*.xls', '*.ppt', '*.pdf')
# ========================================
# FILE MANAGEMENT HELPER FUNCTIONS
# ========================================
<#
.SYNOPSIS
Tests if a file is locked by another process
.DESCRIPTION
Checks if a file can be opened with exclusive access
Returns $true if file is locked, $false if available
.PARAMETER Path
Full path to the file to test
.OUTPUTS
Boolean - $true if locked, $false if available
#>
function Test-FileLock {
param(
[Parameter(Mandatory=$true)]
[string]$Path
)
try {
# Try to open file with exclusive access
$file = [System.IO.File]::Open(
$Path,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None
)
if ($file) {
$file.Close()
$file.Dispose()
return $false # File is NOT locked
}
}
catch [System.IO.IOException] {
# IOException means file is in use
return $true # File IS locked
}
catch {
# Other errors - treat as locked to be safe
Write-Log -Message "Error testing file lock" -Level 'WARNING' -Source 'Test-FileLock' -Context @{ Path = $Path } -Exception $_
return $true
}
return $false
}
<#
.SYNOPSIS
Scans folder for supported files
.DESCRIPTION
Centralized function for scanning folders (sync or async) for supported file types
.PARAMETER FolderPath
Path to folder to scan
.PARAMETER Recursive
Whether to scan subfolders
.OUTPUTS
Array of FileInfo objects
#>
function Get-SupportedFilesFromFolder {
param(
[Parameter(Mandatory=$true)]
[string]$FolderPath,
[Parameter(Mandatory=$false)]
[bool]$Recursive = $false
)
$foundFiles = @()
try {
foreach ($ext in $script:SupportedExtensionPatterns) {
if ($Recursive) {
$foundFiles += Get-ChildItem -Path $FolderPath -Filter $ext -Recurse -File -ErrorAction SilentlyContinue
} else {
$foundFiles += Get-ChildItem -Path $FolderPath -Filter $ext -File -ErrorAction SilentlyContinue
}
}
# Remove duplicates (important!)
$foundFiles = $foundFiles | Sort-Object -Property FullName -Unique
} catch {
Write-Log -Message "Folder scan failed" -Level 'ERROR' -Source 'Get-SupportedFilesFromFolder' -Context @{ FolderPath = $FolderPath; Recursive = $Recursive } -Exception $_
throw
}
return $foundFiles
}
<#
.SYNOPSIS
Merges new files with existing selection, avoiding duplicates
.DESCRIPTION
Centralized logic for merging file selections throughout the app
.PARAMETER NewFiles
Array of FileInfo objects or file paths to add
.PARAMETER ExistingFiles
Array of existing file paths (defaults to $script:selectedFiles)
.OUTPUTS
Hashtable with MergedFiles, NewCount, DuplicateCount
#>
function Merge-FileSelection {
param(
[Parameter(Mandatory=$true)]
[array]$NewFiles,
[Parameter(Mandatory=$false)]
[array]$ExistingFiles = $null
)
if ($null -eq $ExistingFiles) {
$ExistingFiles = @($script:selectedFiles)
}
# Extract full paths from FileInfo objects if needed
$newPaths = $NewFiles | ForEach-Object {
if ($_ -is [System.IO.FileInfo]) {
$_.FullName
} else {
$_
}
}
# Filter out duplicates
$uniqueNewPaths = $newPaths | Where-Object { $ExistingFiles -notcontains $_ }
# Merge arrays
$mergedFiles = @($ExistingFiles) + @($uniqueNewPaths)
return @{
MergedFiles = $mergedFiles
NewCount = $uniqueNewPaths.Count
TotalCount = $NewFiles.Count
DuplicateCount = $NewFiles.Count - $uniqueNewPaths.Count
}
}
# ========================================
# ASYNC RUNSPACE HELPER FUNCTIONS
# ========================================
function New-FileLabelerRunspacePool {
<#
.SYNOPSIS
Creates optimized runspace pool for async operations
.DESCRIPTION
Sets up runspace pool with proper threading, module imports, and helper functions
#>
param(
[int]$MinRunspaces = 1,
[int]$MaxRunspaces = 4
)
# Limit max runspaces to prevent overwhelming the system
$MaxRunspaces = [Math]::Min($MaxRunspaces, [Math]::Min([Environment]::ProcessorCount, 8))
# Create initial session state
$sessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
# Import PurviewInformationProtection module
$sessionState.ImportPSModule("PurviewInformationProtection")
# Create runspace pool
$pool = [RunspaceFactory]::CreateRunspacePool($MinRunspaces, $MaxRunspaces, $sessionState, $Host)
$pool.ApartmentState = "MTA" # MTA for background workers
$pool.ThreadOptions = "ReuseThread"
$pool.Open()
return $pool
}
function Start-AsyncFolderScan {
<#
.SYNOPSIS
Scans folder asynchronously without blocking UI
.DESCRIPTION
Uses runspace to scan folder recursively and returns PowerShell instance for tracking
#>
param(
[Parameter(Mandatory=$true)]
[string]$FolderPath,
[Parameter(Mandatory=$true)]
[System.Management.Automation.Runspaces.RunspacePool]$RunspacePool,
[Parameter(Mandatory=$true)]
[hashtable]$SharedData,
[bool]$Recursive = $false
)
$scanScript = {
param($Folder, $Recursive, $SharedData)
$extensions = @('*.docx', '*.xlsx', '*.pptx', '*.doc', '*.xls', '*.ppt', '*.pdf')
$foundFiles = @()
try {
foreach ($ext in $extensions) {
if ($Recursive) {
$foundFiles += Get-ChildItem -Path $Folder -Filter $ext -Recurse -File -ErrorAction SilentlyContinue
} else {
$foundFiles += Get-ChildItem -Path $Folder -Filter $ext -File -ErrorAction SilentlyContinue
}
}
# Remove duplicates
$foundFiles = $foundFiles | Sort-Object -Property FullName -Unique
# Update shared data thread-safely
$lockTaken = $false
try {
[System.Threading.Monitor]::Enter($SharedData.SyncRoot, [ref]$lockTaken)
foreach ($file in $foundFiles) {
if (-not $SharedData.ScannedFiles.Contains($file.FullName)) {
[void]$SharedData.ScannedFiles.Add($file.FullName)
}
}
$SharedData.ScanComplete = $true
$SharedData.ScanSuccess = $true
} finally {
if ($lockTaken) {
[System.Threading.Monitor]::Exit($SharedData.SyncRoot)
}
}
return $foundFiles.Count
} catch {
# Update shared data with error
$lockTaken = $false
try {
[System.Threading.Monitor]::Enter($SharedData.SyncRoot, [ref]$lockTaken)
$SharedData.ScanComplete = $true
$SharedData.ScanSuccess = $false
$SharedData.ScanError = $_.Exception.Message
} finally {
if ($lockTaken) {
[System.Threading.Monitor]::Exit($SharedData.SyncRoot)
}
}
throw
}
}
# Create PowerShell instance
$ps = [PowerShell]::Create()
$ps.RunspacePool = $RunspacePool
[void]$ps.AddScript($scanScript)
[void]$ps.AddParameter("Folder", $FolderPath)
[void]$ps.AddParameter("Recursive", $Recursive)
[void]$ps.AddParameter("SharedData", $SharedData)
# Start async execution
$handle = $ps.BeginInvoke()
return @{
PowerShell = $ps
Handle = $handle
StartTime = Get-Date
}
}
function Start-AsyncLabelRetrieval {
<#
.SYNOPSIS
Retrieves file labels asynchronously in batches
.DESCRIPTION
Processes file labels in parallel using runspace pool with progress tracking
#>
param(
[Parameter(Mandatory=$true)]
[string[]]$FilePaths,
[Parameter(Mandatory=$true)]
[System.Management.Automation.Runspaces.RunspacePool]$RunspacePool,
[Parameter(Mandatory=$true)]
[hashtable]$SharedCache,
[Parameter(Mandatory=$true)]
[hashtable]$SharedProgress,
[array]$AvailableLabels
)
$labelRetrievalScript = {
param($FilePath, $SharedCache, $SharedProgress, $Labels)
# === CRITICAL: RUNSPACE-LEVEL ERROR HANDLER ===
# Prevent runspace termination from killing the entire process
$ErrorActionPreference = 'Continue'
$result = @{
FilePath = $FilePath
Success = $false
DisplayName = "Ukjent"
LabelId = $null
Rank = -1
}
try {
# ULTIMATE WRAPPER: Catch everything in this runspace
try {
# Check cache first (thread-safe read with lock)
$lockTaken = $false
try {
[System.Threading.Monitor]::Enter($SharedCache.SyncRoot, [ref]$lockTaken)
if ($SharedCache.ContainsKey($FilePath)) {
$cached = $SharedCache[$FilePath]
$result.Success = $true
$result.DisplayName = $cached.DisplayName
$result.LabelId = $cached.LabelId
$result.Rank = $cached.Rank
# Increment progress (thread-safe) - suppress output with [void]
[void][System.Threading.Interlocked]::Increment([ref]$SharedProgress.Processed)
return $result
}
} finally {
if ($lockTaken) {
[System.Threading.Monitor]::Exit($SharedCache.SyncRoot)
}
}
# Retrieve label from AIP
# Don't use SilentlyContinue - let errors be caught by outer try/catch
$labelStatus = Get-AIPFileStatus -Path $FilePath
if ($labelStatus -and $labelStatus.MainLabelId) {
$labelObj = $Labels | Where-Object { $_.Id -eq $labelStatus.MainLabelId }
if ($labelObj) {
$result.Success = $true
$result.DisplayName = $labelObj.DisplayName
$result.LabelId = $labelStatus.MainLabelId
$result.Rank = if($labelObj.Rank) { $labelObj.Rank } else { 0 }
} else {
# Label ID exists but not found in configuration
# This can happen with encrypted/protected labels not in labels_config.json
$result.Success = $true
$result.DisplayName = "Ukjent etikett (beskyttet)"
$result.LabelId = $labelStatus.MainLabelId
$result.Rank = -1
}
} else {
# No label found
$result.Success = $true
$result.DisplayName = "Ingen etikett"
}
# Update cache (thread-safe write)
$lockTaken = $false
try {
[System.Threading.Monitor]::Enter($SharedCache.SyncRoot, [ref]$lockTaken)
$SharedCache[$FilePath] = @{
DisplayName = $result.DisplayName
LabelId = $result.LabelId
Rank = $result.Rank
}
} finally {
if ($lockTaken) {
[System.Threading.Monitor]::Exit($SharedCache.SyncRoot)
}
}
} catch {
# Enhanced error logging for diagnostics
# Note: Cannot use Write-Log in runspace, store error details for later analysis
$result.Success = $false
$result.DisplayName = "Feil ved henting"
$result.ErrorType = $_.Exception.GetType().Name
$result.ErrorMessage = $_.Exception.Message
}
} catch {
# === ULTIMATE LABEL RETRIEVAL CATCH ===
# Catches ANYTHING that escaped all other handlers
# Prevents runspace termination during label retrieval
# Ensure result has required fields
if (-not $result.FilePath) { $result.FilePath = $FilePath }
if (-not $result.DisplayName) { $result.DisplayName = "Runspace feil" }
$result.Success = $false
$result.ErrorType = $_.Exception.GetType().FullName
$result.ErrorMessage = "LABEL RETRIEVAL CRASH: $($_.Exception.Message)"
}
# Increment progress (thread-safe) - suppress output with [void]
[void][System.Threading.Interlocked]::Increment([ref]$SharedProgress.Processed)
return $result
}
# Start jobs for all files
$jobs = @()
foreach ($filePath in $FilePaths) {
$ps = [PowerShell]::Create()
$ps.RunspacePool = $RunspacePool
[void]$ps.AddScript($labelRetrievalScript)
[void]$ps.AddParameter("FilePath", $filePath)
[void]$ps.AddParameter("SharedCache", $SharedCache)
[void]$ps.AddParameter("SharedProgress", $SharedProgress)
[void]$ps.AddParameter("Labels", $AvailableLabels)
$handle = $ps.BeginInvoke()
$jobs += [PSCustomObject]@{
PowerShell = $ps
Handle = $handle
FilePath = $filePath
}
}
return $jobs
}
function Update-UIThreadSafe {
<#
.SYNOPSIS
Safely updates UI control from any thread
.DESCRIPTION
Checks if invoke is required and marshals update to UI thread
#>
param(
[Parameter(Mandatory=$true)]
[System.Windows.Forms.Control]$Control,
[Parameter(Mandatory=$true)]
[scriptblock]$UpdateAction
)
if ($Control.InvokeRequired) {
$Control.Invoke([Action]$UpdateAction)
} else {
& $UpdateAction
}
}
function Wait-AsyncJobsWithUI {
<#
.SYNOPSIS
Waits for async jobs while keeping UI responsive
.DESCRIPTION
Monitors job completion and updates progress bar, allowing UI to process events
#>
param(
[Parameter(Mandatory=$true)]
[array]$Jobs,
[Parameter(Mandatory=$true)]
[hashtable]$SharedProgress,
[Parameter(Mandatory=$true)]
[System.Windows.Forms.ProgressBar]$ProgressBar,
[Parameter(Mandatory=$true)]
[System.Windows.Forms.Label]$StatusLabel,
[Parameter(Mandatory=$true)]
[System.Windows.Forms.Form]$Form,
[int]$UpdateIntervalMs = 100,
[string]$OperationType = "Behandler"
)
$results = @()
$totalJobs = $Jobs.Count
$startTime = Get-Date
# Monitor until all jobs complete
while ($true) {
$completed = 0
foreach ($job in $Jobs) {
if ($job.Handle.IsCompleted) {
$completed++
}
}
# Calculate percentage and elapsed time
$percentComplete = if ($totalJobs -gt 0) { [int](($completed / $totalJobs) * 100) } else { 0 }
$elapsedSeconds = [int]((Get-Date) - $startTime).TotalSeconds
# Calculate estimated time remaining
$estimatedTotal = if ($completed -gt 0) {
($elapsedSeconds / $completed) * $totalJobs
} else {
0
}
$remainingSeconds = [Math]::Max(0, [int]($estimatedTotal - $elapsedSeconds))
# Update UI with detailed progress
Update-UIThreadSafe -Control $ProgressBar -UpdateAction {
$ProgressBar.Value = [Math]::Min(100, $percentComplete)
}
Update-UIThreadSafe -Control $StatusLabel -UpdateAction {
# Enhanced status with percentage and time estimate
$statusText = "$OperationType $completed av $totalJobs ($percentComplete%)"
if ($remainingSeconds -gt 0 -and $completed -gt 5) {
if ($remainingSeconds -lt 60) {
$statusText += " - ca. $remainingSeconds sek gjenstår"
} else {
$minutes = [Math]::Ceiling($remainingSeconds / 60)
$statusText += " - ca. $minutes min gjenstår"
}
}
$StatusLabel.Text = $statusText
}
# Allow UI to process events
[System.Windows.Forms.Application]::DoEvents()
# Check if all complete
if ($completed -eq $totalJobs) {
break
}
Start-Sleep -Milliseconds $UpdateIntervalMs
}
# Collect results
$collectedCount = 0
foreach ($job in $Jobs) {
try {
# Check if job completed successfully
if ($job.Handle.IsCompleted) {
try {
$result = $job.PowerShell.EndInvoke($job.Handle)
if ($result) {
$results += $result
$collectedCount++
}
} catch {
Write-Log -Message "EndInvoke failed for job" -Level 'WARNING' -Source 'Wait-AsyncJobsWithUI' -Context @{ FilePath = $job.FilePath } -Exception $_
# Check PowerShell streams for errors
if ($job.PowerShell.Streams.Error.Count -gt 0) {
foreach ($err in $job.PowerShell.Streams.Error) {
Write-Log -Message "Runspace error detected" -Level 'ERROR' -Source 'Wait-AsyncJobsWithUI' -Context @{ FilePath = $job.FilePath; ErrorMessage = $err.Exception.Message }
}
}
}
} else {
Write-Log -Message "Job not completed" -Level 'WARNING' -Source 'Wait-AsyncJobsWithUI' -Context @{ FilePath = $job.FilePath }
}
} catch {
Write-Log -Message "Critical error in result collection" -Level 'ERROR' -Source 'Wait-AsyncJobsWithUI' -Context @{ FilePath = $job.FilePath } -Exception $_
} finally {
# Always dispose, even if errors
try {
if ($job.PowerShell) {
$job.PowerShell.Dispose()
}
} catch {
Write-Log -Message "Could not dispose PowerShell instance" -Level 'WARNING' -Source 'Wait-AsyncJobsWithUI' -Exception $_
}
}
}