-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOutlookAutoArchive.ps1
More file actions
1741 lines (1540 loc) · 88.8 KB
/
OutlookAutoArchive.ps1
File metadata and controls
1741 lines (1540 loc) · 88.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
Auto-archive Outlook emails with options from config.json
.DESCRIPTION
This PowerShell script automatically archives old emails from Outlook accounts based on configurable retention periods.
It supports both regular email accounts (using folders) and Gmail accounts (using labels).
Key Features:
- Configurable retention periods (default: 14 days)
- Dry-run mode for testing before actual archiving
- Support for Gmail labels and regular email folders
- Automatic folder creation (year/month structure)
- Skip rules for specific subjects or mailboxes
- Comprehensive logging
- Windows Task Scheduler integration
- First-run setup wizard
.PARAMETER None
This script uses configuration from config.json file
.EXAMPLE
.\OutlookAutoArchive.ps1
Runs the script with settings from config.json
.NOTES
Version: 2.9.5
Author: Ryan Zeffiretti
License: MIT
Requires: Microsoft Outlook to be running
Requires: PowerShell 5.1 or later
Installation:
- First run installs to C:\Users\$env:USERNAME\OutlookAutoArchive
- Creates config.json with default settings
- Sets up archive folders/labels for each email account
Configuration:
- Edit config.json to change retention days, dry-run mode, etc.
- Set 'DryRun': false when ready for live archiving
- Logs are stored in the Logs folder within installation directory
#>
# Version: 2.9.5
# Author: Ryan Zeffiretti
# Description: Auto-archive Outlook emails with options from config.json
# License: MIT
# Last Updated: 2025-08-14
# =============================================================================
# OUTLOOK INTEROP ASSEMBLY LOADING
# =============================================================================
# Try to load Outlook Interop assembly, but don't fail if it's not available
# This provides better type safety and IntelliSense support when available
# If not available, we fall back to COM objects which work in all environments
try {
Add-Type -AssemblyName Microsoft.Office.Interop.Outlook -ErrorAction SilentlyContinue
Write-Host "[OK] Outlook Interop assembly loaded successfully" -ForegroundColor Green
}
catch {
Write-Host "Note: Microsoft.Office.Interop.Outlook assembly not found, will use COM objects directly" -ForegroundColor Yellow
}
# Initialize Outlook COM objects (will be set up later when needed)
# These are global variables that will be populated when we connect to Outlook
$outlook = $null # Main Outlook application object
$namespace = $null # MAPI namespace for accessing folders and accounts
# =============================================================================
# WINDOWS SECURITY - EXECUTABLE UNBLOCKING
# =============================================================================
# Windows automatically blocks executables downloaded from the internet for security
# This section detects if the executable is blocked and attempts to unblock it
# This is essential for user experience when downloading from GitHub or other sources
try {
# Determine the path to the executable (works for both .ps1 and compiled .exe)
$currentExePath = if ($PSScriptRoot) { Join-Path $PSScriptRoot "OutlookAutoArchive.exe" } else { Join-Path (Get-Location) "OutlookAutoArchive.exe" }
if (Test-Path $currentExePath) {
# Check for Zone.Identifier alternate data stream (indicates internet download)
$zoneInfo = Get-ItemProperty -Path $currentExePath -Name Zone.Identifier -ErrorAction SilentlyContinue
if ($zoneInfo -and $zoneInfo.'Zone.Identifier') {
Write-Host ""
Write-Host "[!] Windows has blocked this executable because it was downloaded from the internet." -ForegroundColor Yellow
Write-Host "Attempting to unblock the file automatically..." -ForegroundColor Cyan
try {
# Use PowerShell's Unblock-File cmdlet to remove the block
Unblock-File -Path $currentExePath -ErrorAction Stop
Write-Host "[OK] Successfully unblocked the executable!" -ForegroundColor Green
Write-Host "You can now run the application normally." -ForegroundColor White
}
catch {
# If automatic unblocking fails, provide manual instructions
Write-Host "[ERROR] Could not automatically unblock the file." -ForegroundColor Red
Write-Host ""
Write-Host "To unblock manually:" -ForegroundColor Cyan
Write-Host "1. Right-click on OutlookAutoArchive.exe" -ForegroundColor White
Write-Host "2. Select 'Properties'" -ForegroundColor White
Write-Host "3. Check 'Unblock' at the bottom of the dialog" -ForegroundColor White
Write-Host "4. Click 'OK'" -ForegroundColor White
Write-Host "5. Run the application again" -ForegroundColor White
Write-Host ""
Write-Host "Press any key to continue anyway..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
}
}
catch {
Write-Host "Note: Could not check for Windows blocking status" -ForegroundColor Gray
}
# =============================================================================
# CONFIGURATION LOADING AND INITIALIZATION
# =============================================================================
# This section handles loading the configuration file and setting up default values
# The config.json file stores user preferences and discovered archive folder paths
# Determine the installation directory (hardcoded for consistency)
$installPath = "C:\Users\$env:USERNAME\OutlookAutoArchive"
$configPath = Join-Path $installPath 'config.json'
$scriptDir = $installPath # Set script directory for normal operation
Write-Host "Installation directory: $installPath"
Write-Host "Config path: $configPath"
# Initialize config object (will be populated from file or defaults)
$config = $null
# Try to load existing configuration file
if (Test-Path $configPath) {
try {
# Read and parse the JSON configuration file
$config = Get-Content $configPath -Raw | ConvertFrom-Json
Write-Host "[OK] Loaded existing configuration" -ForegroundColor Green
}
catch {
# Handle corrupted or invalid JSON files
Write-Host "[!] Invalid JSON in config.json, will create new configuration" -ForegroundColor Yellow
$config = $null
}
}
# If no config exists or is invalid, initialize with safe default values
if (-not $config) {
Write-Host "No valid configuration found. Initializing with default settings." -ForegroundColor Cyan
$config = @{
RetentionDays = 14 # Days to keep emails in Inbox before archiving
DryRun = $true # Safety mode - don't actually move emails
LogPath = "./Logs" # Relative path for log files
GmailLabel = "OutlookArchive" # Label name for Gmail accounts
OnFirstRun = $true # Flag to trigger first-run setup wizard
ArchiveFolders = @{} # Hash table of discovered archive folder paths
MonitoringInterval = 4 # Hours between continuous monitoring runs
SkipRules = @( # Rules to skip archiving specific emails
@{
Mailbox = "Your Mailbox Name" # Example skip rule
Subjects = @("Subject Pattern 1", "Subject Pattern 2")
}
)
}
}
# =============================================================================
# FIRST RUN SETUP WIZARD
# =============================================================================
# This section handles the initial setup when the script is run for the first time
# It guides users through configuration, creates archive folders, and sets up scheduling
if ($config.OnFirstRun -eq $true) {
# ASCII Art Banner
Write-Host ""
Write-Host "╔══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║ ║" -ForegroundColor Cyan
Write-Host "║ OUTLOOK AUTO ARCHIVE - FIRST RUN ║" -ForegroundColor Cyan
Write-Host "║ Welcome to Your Email Archiving Setup ║" -ForegroundColor Cyan
Write-Host "║ ║" -ForegroundColor Cyan
Write-Host "╚══════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
Write-Host ""
Write-Host "[TARGET] This appears to be your first time running the script." -ForegroundColor White
Write-Host "[STEPS] Let's set up your archive folders and configuration." -ForegroundColor White
Write-Host ""
# =================================================================
# ADMIN RIGHTS CHECK FOR SCHEDULED TASK CREATION
# =================================================================
# Check admin rights early for scheduling setup
# Windows Task Scheduler requires admin privileges to create tasks
Write-Host "[SEARCH] Checking system requirements..." -ForegroundColor Cyan
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $isAdmin) {
Write-Host "[!] Note: You're not running as Administrator" -ForegroundColor Yellow
Write-Host "This is fine for normal usage, but you'll need admin rights for scheduled task creation." -ForegroundColor White
Write-Host "You can:" -ForegroundColor Cyan
Write-Host "1. Continue with setup (you can set up scheduling later with admin rights)" -ForegroundColor White
Write-Host "2. Restart as Administrator now" -ForegroundColor White
Write-Host ""
# Get user choice for admin rights handling
do {
$adminChoice = Read-Host "Continue with setup or restart as Administrator? (1/2)"
if ($adminChoice -match '^[1-2]$') {
break
}
Write-Host "Please enter 1 or 2." -ForegroundColor Red
} while ($true)
if ($adminChoice -eq '2') {
# Restart the script with elevated privileges
Write-Host "Restarting with admin rights..." -ForegroundColor Yellow
$scriptPath = if ($PSScriptRoot) { Join-Path $PSScriptRoot "OutlookAutoArchive.exe" } else { Join-Path (Get-Location) "OutlookAutoArchive.exe" }
Start-Process -FilePath $scriptPath -Verb RunAs
exit 0
}
else {
Write-Host "Continuing with setup. You can set up scheduling later with admin rights." -ForegroundColor Green
Write-Host ""
}
}
else {
Write-Host "[OK] Running with Administrator privileges - all features available" -ForegroundColor Green
Write-Host ""
}
# =================================================================
# INSTALLATION DIRECTORY SETUP
# =================================================================
# Set installation location to user's home directory for consistency
# This ensures the app always knows where it's installed
$currentLocation = if ($PSScriptRoot) { $PSScriptRoot } else { Get-Location }
$installPath = "C:\Users\$env:USERNAME\OutlookAutoArchive"
Write-Host "Installation location: $installPath" -ForegroundColor Green
# Check if we need to move files from current location to installation directory
if ($installPath -ne $currentLocation) {
Write-Host ""
Write-Host "Setting up installation at: $installPath" -ForegroundColor Cyan
try {
# Create the installation directory if it doesn't exist
if (-not (Test-Path $installPath)) {
New-Item -Path $installPath -ItemType Directory -Force | Out-Null
Write-Host "[OK] Created installation directory" -ForegroundColor Green
}
# Copy only essential files to the installation location
# We only copy the executable - config.json will be created during setup
$filesToCopy = @(
"OutlookAutoArchive.exe" # Main application executable
)
$filesCopied = 0
foreach ($file in $filesToCopy) {
$sourceFile = Join-Path $currentLocation $file
$destFile = Join-Path $installPath $file
if (Test-Path $sourceFile) {
Copy-Item -Path $sourceFile -Destination $destFile -Force
$filesCopied++
}
}
Write-Host "[OK] Copied $filesCopied files to installation directory" -ForegroundColor Green
# Create a simple README.txt for users with essential information
# This provides users with quick start instructions and troubleshooting help
$readmeContent = @"
Outlook Auto Archive - Version 2.9.0
====================================
This application automatically archives old emails from your Outlook accounts.
QUICK START:
1. Double-click OutlookAutoArchive.exe to run
2. If Windows blocks the file, the app will attempt to unblock it automatically
3. Follow the setup wizard to configure your preferences
4. The app will create a config.json file with your settings
5. Check the Logs folder for operation details
WINDOWS SECURITY:
- If Windows blocks the executable, the app will try to unblock it automatically
- If automatic unblocking fails, right-click the .exe file → Properties → Check "Unblock"
- This is normal for files downloaded from the internet
CONFIGURATION:
- Edit config.json to change settings (retention days, dry-run mode, etc.)
- Set 'DryRun': false when ready to archive emails for real
- Logs are stored in the Logs folder within this directory
SUPPORT:
- For help and updates, visit the original repository
- Check the Logs folder for troubleshooting information
Version 2.9.0 - Fixed LogPath handling and improved path processing
"@
$readmePath = Join-Path $installPath "README.txt"
$readmeContent | Out-File -FilePath $readmePath -Encoding UTF8
Write-Host "[OK] Created user-friendly README.txt" -ForegroundColor Green
# Update the script directory for the rest of the setup
$scriptDir = $installPath
$configPath = Join-Path $installPath 'config.json'
Write-Host ""
Write-Host "Installation completed successfully!" -ForegroundColor Green
Write-Host "The application is now installed at: $installPath" -ForegroundColor White
Write-Host ""
Write-Host "Note: You can now delete the original files from: $currentLocation" -ForegroundColor Yellow
Write-Host "The application will run from the new location." -ForegroundColor White
Write-Host ""
}
catch {
Write-Host "[ERROR] Error during installation: $_" -ForegroundColor Red
Write-Host "Continuing with installation directory..." -ForegroundColor Yellow
$scriptDir = $installPath
$configPath = Join-Path $installPath 'config.json'
}
}
else {
# Use installation directory
$scriptDir = $installPath
$configPath = Join-Path $installPath 'config.json'
}
# =================================================================
# OUTLOOK CONNECTION AND VALIDATION
# =================================================================
# Check if Outlook is running before attempting to connect
# This prevents errors and provides clear user feedback
try {
$outlookProcesses = Get-Process -Name "OUTLOOK" -ErrorAction SilentlyContinue
if (-not $outlookProcesses) {
Write-Host "[ERROR] Outlook is not running. Please start Outlook and run the script again." -ForegroundColor Red
Write-Host "The setup requires Outlook to be running to access your email accounts." -ForegroundColor Yellow
exit 1
}
Write-Host "[OK] Outlook is running" -ForegroundColor Green
}
catch {
Write-Host "[!] Could not check Outlook status. Proceeding anyway..." -ForegroundColor Yellow
}
# Connect to Outlook using COM objects
# This establishes the connection needed to access email accounts and folders
try {
$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNamespace("MAPI")
Write-Host "[OK] Connected to Outlook" -ForegroundColor Green
}
catch {
Write-Host "[ERROR] Failed to connect to Outlook: $_" -ForegroundColor Red
Write-Host "Make sure Outlook is running and you have the necessary permissions." -ForegroundColor Yellow
exit 1
}
# =================================================================
# EMAIL ACCOUNT DISCOVERY AND CLASSIFICATION
# =================================================================
# Scan all Outlook accounts and classify them as Gmail or regular accounts
# This helps determine the appropriate archiving method (labels vs folders)
Write-Host ""
Write-Host "[EMAIL] Scanning your email accounts..." -ForegroundColor Cyan
$accounts = @() # All discovered accounts
$gmailAccounts = @() # Gmail accounts (use labels)
$regularAccounts = @() # Regular email accounts (use folders)
foreach ($account in $namespace.Folders) {
$accounts += $account.Name
# Check if this looks like a Gmail account based on email domain
$isGmail = $account.Name -like "*@gmail.com" -or $account.Name -like "*@googlemail.com" -or $account.Name -like "*@gmail.co.uk"
if ($isGmail) {
$gmailAccounts += $account.Name
}
else {
$regularAccounts += $account.Name
}
}
Write-Host "[OK] Found $($accounts.Count) email account(s):" -ForegroundColor Green
foreach ($account in $accounts) {
Write-Host " [EMAIL] $account" -ForegroundColor White
}
if ($gmailAccounts.Count -gt 0) {
Write-Host ""
Write-Host "[SEARCH] Gmail accounts detected: $($gmailAccounts -join ', ')" -ForegroundColor Yellow
Write-Host "[TIP] Note: Gmail accounts will use labels instead of folders for archiving." -ForegroundColor Gray
}
Write-Host ""
# =================================================================
# RETENTION PERIOD CONFIGURATION
# =================================================================
# Get user preference for how long emails should stay in Inbox before archiving
# This is a critical setting that affects which emails get moved
Write-Host ""
Write-Host "[TIME] RETENTION PERIOD CONFIGURATION:" -ForegroundColor Yellow
Write-Host "How many days should emails stay in your Inbox before being archived?" -ForegroundColor Cyan
Write-Host "[TIP] Recommended: 14-30 days" -ForegroundColor Gray
Write-Host ""
do {
$retentionInput = Read-Host "Enter number of days (default: 14)"
if ([string]::IsNullOrWhiteSpace($retentionInput)) {
$retentionDays = 14
break
}
if ($retentionInput -match '^\d+$' -and [int]$retentionInput -gt 0) {
$retentionDays = [int]$retentionInput
break
}
Write-Host "[ERROR] Please enter a valid positive number." -ForegroundColor Red
} while ($true)
Write-Host "[OK] Retention period set to $retentionDays days" -ForegroundColor Green
# =================================================================
# GMAIL LABEL CONFIGURATION
# =================================================================
# Configure custom label name for Gmail accounts
# Gmail doesn't allow "Archive" as a label name, so we use a custom name
$gmailLabel = "OutlookArchive"
if ($gmailAccounts.Count -gt 0) {
Write-Host ""
Write-Host "[LABEL] GMAIL LABEL CONFIGURATION:" -ForegroundColor Yellow
Write-Host "For Gmail accounts, what would you like to call your archive label?" -ForegroundColor Cyan
Write-Host "[!] Note: 'Archive' is not allowed in Gmail, so we use a custom label name." -ForegroundColor Gray
Write-Host "[TIP] Recommended: OutlookArchive, MyArchive, or EmailArchive" -ForegroundColor Gray
Write-Host ""
do {
$labelInput = Read-Host "Enter label name (default: OutlookArchive)"
if ([string]::IsNullOrWhiteSpace($labelInput)) {
$gmailLabel = "OutlookArchive"
break
}
if ($labelInput -match '^[a-zA-Z0-9_-]+$') {
$gmailLabel = $labelInput
break
}
Write-Host "[ERROR] Please enter a valid label name (letters, numbers, hyphens, underscores only)." -ForegroundColor Red
} while ($true)
Write-Host "[OK] Gmail archive label set to '$gmailLabel'" -ForegroundColor Green
}
# =================================================================
# ARCHIVE FOLDER AND LABEL SETUP
# =================================================================
# Check for existing archive folders/labels and create any missing ones
# This ensures the archiving process has a destination for each account
Write-Host ""
Write-Host "[FOLDER] ARCHIVE FOLDER SETUP:" -ForegroundColor Yellow
Write-Host "Now let's check for existing archive folders and create any missing ones..." -ForegroundColor Cyan
$foldersCreated = 0 # Counter for successfully created folders/labels
$errors = 0 # Counter for errors encountered during setup
foreach ($account in $namespace.Folders) {
try {
Write-Host ""
Write-Host "Processing account: $($account.Name)" -ForegroundColor Cyan
# Skip non-email account types that can't be archived
# These account types don't contain emails and would cause errors
$skipAccountTypes = @("Internet Calendars", "SharePoint Lists", "Public Folders", "Calendar", "Contacts", "Tasks", "Notes")
if ($skipAccountTypes -contains $account.Name) {
Write-Host " [!] Skipping non-email account type: $($account.Name)" -ForegroundColor Yellow
continue
}
# Check if this looks like a Gmail account based on email domain
$isGmail = $account.Name -like "*@gmail.com" -or $account.Name -like "*@googlemail.com" -or $account.Name -like "*@gmail.co.uk"
if ($isGmail) {
Write-Host " Detected Gmail account" -ForegroundColor Gray
# Gmail accounts use labels instead of folders for organization
# Check if the Gmail label already exists
$existingLabel = $null
try {
$existingLabel = $account.Folders.Item($gmailLabel)
}
catch {}
if ($existingLabel) {
Write-Host " [OK] Gmail label '$gmailLabel' already exists" -ForegroundColor Green
# Store the Gmail label path in config for future use
$config.ArchiveFolders[$account.Name] = "GmailLabel:$gmailLabel"
}
else {
Write-Host " Gmail label '$gmailLabel' not found" -ForegroundColor Yellow
$createLabel = Read-Host " Would you like to create it? (Y/N)"
if ($createLabel -eq 'Y' -or $createLabel -eq 'y') {
try {
# Create the Gmail label
$account.Folders.Add($gmailLabel)
Write-Host " [OK] Created Gmail label '$gmailLabel'" -ForegroundColor Green
$foldersCreated++
# Store the Gmail label path in config for future use
$config.ArchiveFolders[$account.Name] = "GmailLabel:$gmailLabel"
}
catch {
# Gmail label creation can sometimes throw errors but still succeed
# Check if the label was actually created despite the error
try {
$testLabel = $account.Folders.Item($gmailLabel)
if ($testLabel) {
Write-Host " [OK] Gmail label '$gmailLabel' was created successfully" -ForegroundColor Green
$foldersCreated++
# Store the Gmail label path in config for future use
$config.ArchiveFolders[$account.Name] = "GmailLabel:$gmailLabel"
}
}
catch {
Write-Host " [!] Gmail label creation encountered an issue, but this is often normal for Gmail accounts" -ForegroundColor Yellow
Write-Host " The label may still be available in Outlook. You can check manually or try again later." -ForegroundColor Gray
$errors++
}
}
}
else {
Write-Host " [!] Skipped creating Gmail label" -ForegroundColor Yellow
}
}
}
else {
Write-Host " Detected regular email account" -ForegroundColor Gray
# Regular email accounts use folders for organization
# Check for existing archive folder in common locations
$archiveFolder = $null
# Check root level first (most common location)
try {
$archiveFolder = $account.Folders.Item("Archive")
Write-Host " [OK] Archive folder already exists at root level" -ForegroundColor Green
# Store the archive folder path in config for future use
$config.ArchiveFolders[$account.Name] = "Root:Archive"
}
catch {
# Check Inbox\Archive as alternative location
try {
$inbox = $account.Folders.Item("Inbox")
if ($inbox) {
$archiveFolder = $inbox.Folders.Item("Archive")
Write-Host " [OK] Archive folder already exists in Inbox" -ForegroundColor Green
# Store the archive folder path in config for future use
$config.ArchiveFolders[$account.Name] = "Inbox:Archive"
}
}
catch {}
# If no archive folder found, ask user where to create it
if (-not $archiveFolder) {
Write-Host " No Archive folder found" -ForegroundColor Yellow
Write-Host " Where would you like to create the Archive folder?" -ForegroundColor Cyan
Write-Host " 1. Root level (recommended)" -ForegroundColor White
Write-Host " 2. Inside Inbox folder" -ForegroundColor White
Write-Host " 3. Skip this account" -ForegroundColor White
# Get user preference for archive folder location
do {
$locationChoice = Read-Host " Enter choice (1-3)"
if ($locationChoice -match '^[1-3]$') {
break
}
Write-Host " Please enter 1, 2, or 3." -ForegroundColor Red
} while ($true)
if ($locationChoice -eq '1') {
# Create archive folder at root level (recommended)
try {
$archiveFolder = $account.Folders.Add("Archive")
Write-Host " [OK] Created Archive folder at root level" -ForegroundColor Green
$foldersCreated++
# Store the archive folder path in config for future use
$config.ArchiveFolders[$account.Name] = "Root:Archive"
}
catch {
Write-Host " [ERROR] Failed to create Archive folder: $_" -ForegroundColor Red
$errors++
}
}
elseif ($locationChoice -eq '2') {
# Create archive folder inside Inbox folder
try {
$inbox = $account.Folders.Item("Inbox")
if ($inbox) {
$archiveFolder = $inbox.Folders.Add("Archive")
Write-Host " [OK] Created Archive folder in Inbox" -ForegroundColor Green
$foldersCreated++
# Store the archive folder path in config for future use
$config.ArchiveFolders[$account.Name] = "Inbox:Archive"
}
else {
Write-Host " [ERROR] Could not access Inbox folder" -ForegroundColor Red
$errors++
}
}
catch {
Write-Host " [ERROR] Failed to create Archive folder: $_" -ForegroundColor Red
$errors++
}
}
else {
Write-Host " [!] Skipped creating Archive folder" -ForegroundColor Yellow
}
}
}
}
}
catch {
Write-Host " [ERROR] Error processing account '$($account.Name)': $_" -ForegroundColor Red
$errors++
}
}
# =================================================================
# SETUP SUMMARY AND CONFIGURATION SAVING
# =================================================================
# Display summary of what was accomplished during setup
Write-Host ""
Write-Host "╔══════════════════════════════════════════════════════════════╗" -ForegroundColor Green
Write-Host "║ SETUP SUMMARY ║" -ForegroundColor Green
Write-Host "╚══════════════════════════════════════════════════════════════╝" -ForegroundColor Green
Write-Host ""
Write-Host "[EMAIL] Accounts processed: $($accounts.Count)" -ForegroundColor White
Write-Host "[FOLDER] Folders/labels created: $foldersCreated" -ForegroundColor White
Write-Host "[ERROR] Errors encountered: $errors" -ForegroundColor $(if ($errors -gt 0) { "Red" } else { "Green" })
# Update configuration object with user preferences from setup
$config.RetentionDays = $retentionDays
$config.GmailLabel = $gmailLabel
$config.OnFirstRun = $false # Mark first run as complete
# Save monitoring interval if it was set during setup
if ($monitoringInterval) {
$config.MonitoringInterval = $monitoringInterval
}
# Ensure installation directory exists before saving config
if (-not (Test-Path $installPath)) {
New-Item -Path $installPath -ItemType Directory -Force | Out-Null
Write-Host "Created installation directory: $installPath" -ForegroundColor Green
}
# Save updated configuration with discovered archive folder paths
# This is crucial for future runs to avoid re-scanning for folders
try {
$config | ConvertTo-Json -Depth 3 | Out-File $configPath -Encoding UTF8
Write-Host "[OK] Configuration saved with archive folder paths" -ForegroundColor Green
Write-Host "Archive folders discovered and stored for future runs:" -ForegroundColor Cyan
foreach ($accountName in $config.ArchiveFolders.Keys) {
Write-Host " - $accountName`: $($config.ArchiveFolders[$accountName])" -ForegroundColor White
}
}
catch {
Write-Host "[ERROR] Failed to save configuration: $_" -ForegroundColor Red
}
Write-Host ""
Write-Host "[SUCCESS] First run setup completed!" -ForegroundColor Green
Write-Host ""
# =================================================================
# SCHEDULED TASK SETUP
# =================================================================
# Offer to create Windows Task Scheduler tasks for automatic archiving
# This allows the script to run automatically without user intervention
Write-Host "[TIME] SCHEDULED TASK SETUP:" -ForegroundColor Yellow
Write-Host "Would you like to set up automatic scheduling now?" -ForegroundColor Cyan
Write-Host "This will create a Windows Task Scheduler task to run the archive script automatically." -ForegroundColor White
Write-Host ""
Write-Host "[SCHEDULE] Scheduling options:" -ForegroundColor Yellow
Write-Host "┌─────────────────────────────────────────────────────────────────┐" -ForegroundColor Gray
Write-Host "│ 1. DAILY ARCHIVING │" -ForegroundColor White
Write-Host "│ Runs once per day at a specific time (e.g., 2:00 AM) │" -ForegroundColor Gray
Write-Host "│ Best for: Users who want predictable, quiet archiving │" -ForegroundColor Gray
Write-Host "└─────────────────────────────────────────────────────────────────┘" -ForegroundColor Gray
Write-Host ""
Write-Host "┌─────────────────────────────────────────────────────────────────┐" -ForegroundColor Gray
Write-Host "│ 2. SKIP SCHEDULING FOR NOW │" -ForegroundColor White
Write-Host "│ You can set up scheduling later using the setup script │" -ForegroundColor Gray
Write-Host "└─────────────────────────────────────────────────────────────────┘" -ForegroundColor Gray
Write-Host ""
do {
$scheduleChoice = Read-Host "Enter choice (1-2)"
if ($scheduleChoice -match '^[1-2]$') {
break
}
Write-Host "Please enter 1 or 2." -ForegroundColor Red
} while ($true)
if ($scheduleChoice -eq '1') {
Write-Host ""
Write-Host "Setting up daily scheduled task..." -ForegroundColor Cyan
# Get time from user
Write-Host "What time would you like the script to run daily?" -ForegroundColor Cyan
Write-Host "Recommended: 2:00 AM (when you're not using Outlook)" -ForegroundColor Gray
do {
$timeInput = Read-Host "Enter time in 24-hour format (e.g., 02:00 for 2:00 AM)"
if ($timeInput -match '^([01]?[0-9]|2[0-3]):[0-5][0-9]$') {
$scheduledTime = $timeInput
break
}
Write-Host "Please enter a valid time in 24-hour format (HH:MM)." -ForegroundColor Red
} while ($true)
# Create daily scheduled task (admin rights already checked at setup start)
if (-not $isAdmin) {
Write-Host "[!] Admin rights required for scheduled task creation" -ForegroundColor Yellow
Write-Host "You can set up scheduling manually later using Task Scheduler:" -ForegroundColor White
Write-Host "1. Open Task Scheduler (search in Start menu)" -ForegroundColor Gray
Write-Host "2. Click 'Create Basic Task'" -ForegroundColor Gray
Write-Host "3. Name: 'Outlook Auto Archive'" -ForegroundColor Gray
Write-Host "4. Trigger: 'Daily' at $scheduledTime" -ForegroundColor Gray
Write-Host "5. Action: 'Start a program'" -ForegroundColor Gray
Write-Host "6. Program: '$scriptPath'" -ForegroundColor Gray
Write-Host "7. Finish and check 'Open properties dialog'" -ForegroundColor Gray
Write-Host "8. In Properties, go to 'General' tab and check 'Run with highest privileges'" -ForegroundColor Gray
Write-Host "9. Click OK to save" -ForegroundColor Gray
Write-Host ""
Write-Host "The task will run daily at $scheduledTime." -ForegroundColor Green
}
else {
# Create daily scheduled task
try {
$taskName = "Outlook Auto Archive"
$scriptPath = if ($PSScriptRoot) { Join-Path $PSScriptRoot "OutlookAutoArchive.exe" } else { Join-Path (Get-Location) "OutlookAutoArchive.exe" }
# Check if executable exists, fall back to PowerShell script
if (-not (Test-Path $scriptPath)) {
$scriptPath = if ($PSScriptRoot) { Join-Path $PSScriptRoot "OutlookAutoArchive.ps1" } else { Join-Path (Get-Location) "OutlookAutoArchive.ps1" }
$arguments = "-ExecutionPolicy Bypass -File `"$scriptPath`""
$program = "powershell.exe"
}
else {
$arguments = ""
$program = $scriptPath
}
# Create the scheduled task
$createTaskCmd = "schtasks /create /tn `"$taskName`" /tr `"$program`""
if ($arguments) { $createTaskCmd += " /sc daily /st $scheduledTime /f" } else { $createTaskCmd += " /sc daily /st $scheduledTime /f" }
Write-Host "Creating scheduled task..." -ForegroundColor Yellow
Invoke-Expression $createTaskCmd
if ($LASTEXITCODE -eq 0) {
Write-Host "[OK] Daily scheduled task created successfully!" -ForegroundColor Green
Write-Host "Task will run daily at $scheduledTime" -ForegroundColor White
}
else {
Write-Host "[!] Could not create scheduled task automatically." -ForegroundColor Yellow
Write-Host "You can create it manually using Task Scheduler:" -ForegroundColor White
Write-Host "1. Open Task Scheduler" -ForegroundColor Gray
Write-Host "2. Create Basic Task" -ForegroundColor Gray
Write-Host "3. Name: Outlook Auto Archive" -ForegroundColor Gray
Write-Host "4. Trigger: Daily at $scheduledTime" -ForegroundColor Gray
Write-Host "5. Action: Start program: $program" -ForegroundColor Gray
}
}
catch {
Write-Host "[ERROR] Error creating scheduled task: $_" -ForegroundColor Red
Write-Host "You can set up scheduling manually later." -ForegroundColor Yellow
}
}
}
else {
Write-Host ""
Write-Host "Scheduling skipped. You can set it up later using:" -ForegroundColor Yellow
Write-Host "1. Task Scheduler GUI" -ForegroundColor White
Write-Host "2. setup_task_scheduler.exe" -ForegroundColor White
Write-Host "3. Manual schtasks command" -ForegroundColor White
}
Write-Host ""
Write-Host "[STEPS] NEXT STEPS:" -ForegroundColor Yellow
Write-Host "1. The script will now run in dry-run mode to test everything" -ForegroundColor White
Write-Host "2. Check the log files to verify everything works" -ForegroundColor White
Write-Host "3. When ready, edit config.json and set 'DryRun': false" -ForegroundColor White
Write-Host "4. Test your scheduled task if you created one" -ForegroundColor White
Write-Host ""
Write-Host "[!] IMPORTANT: The dry-run test may take several minutes depending on how many emails you have." -ForegroundColor Yellow
Write-Host "This is normal - the script is scanning all your emails to show what would be archived." -ForegroundColor White
Write-Host "Please be patient and don't close the window while it's running." -ForegroundColor White
if ($gmailAccounts.Count -gt 0) {
Write-Host ""
Write-Host "[EMAIL] For Gmail users:" -ForegroundColor Cyan
Write-Host " • Make sure IMAP is enabled in Gmail settings" -ForegroundColor White
Write-Host " • Check 'Show in IMAP' for your labels in Gmail web interface" -ForegroundColor White
Write-Host " • It may take a few minutes for labels to sync to Outlook" -ForegroundColor White
}
Write-Host ""
Write-Host "╔══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║ CONTINUING WITH ARCHIVE PROCESS ║" -ForegroundColor Cyan
Write-Host "╚══════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
Write-Host ""
# Reload config to get the updated values from the first-run setup
try {
$config = Get-Content $configPath -Raw | ConvertFrom-Json
Write-Host "[OK] Configuration reloaded with updated settings" -ForegroundColor Green
}
catch {
Write-Host "[!] Could not reload configuration, continuing with current settings" -ForegroundColor Yellow
}
}
# =============================================================================
# MAIN PROCESSING - CONFIGURATION APPLICATION
# =============================================================================
# Apply configuration settings to variables used throughout the script
# This section runs after first-run setup (if applicable) or loads from existing config
$RetentionDays = [int]$config.RetentionDays # Convert to integer for date calculations
$DryRun = [bool]$config.DryRun # Convert to boolean for conditional logic
# Process log path with proper error handling
$rawLogPath = $config.LogPath
if ([string]::IsNullOrEmpty($rawLogPath)) {
$rawLogPath = ".\Logs"
Write-Host "LogPath was empty, using default: $rawLogPath"
}
# Handle relative paths and environment variables
# First, normalize the path by removing escaped backslashes
$normalizedPath = $rawLogPath -replace '\\\\', '\' # Fix double backslashes
$normalizedPath = $normalizedPath -replace '//', '/' # Fix double forward slashes
if ($normalizedPath -like ".\*" -or $normalizedPath -like "./*") {
# Relative path - make it absolute based on script location
$LogPath = Join-Path $scriptDir $normalizedPath.Substring(2)
}
else {
# Handle environment variables for absolute paths
$LogPath = $normalizedPath -replace '%USERPROFILE%', $env:USERPROFILE
}
# Ensure LogPath is never null or empty
if ([string]::IsNullOrEmpty($LogPath)) {
$LogPath = Join-Path $scriptDir "Logs"
Write-Host "LogPath processing failed, using fallback: $LogPath"
}
# Ensure the LogPath is absolute
if (-not [System.IO.Path]::IsPathRooted($LogPath)) {
$LogPath = Join-Path $scriptDir $LogPath
}
Write-Host "Using log path: $LogPath"
# Calculate date-based variables for archiving logic
$Today = Get-Date
$CutOff = $Today.AddDays(-$RetentionDays) # Date threshold for archiving
Write-Host "Retention period: $RetentionDays days" -ForegroundColor Cyan
Write-Host "Cutoff date: $CutOff (emails older than this will be archived)" -ForegroundColor Cyan
$GmailLabel = $config.GmailLabel # Label name for Gmail accounts
$SkipRules = $config.SkipRules # Rules for skipping specific emails
# =============================================================================
# OUTLOOK AVAILABILITY CHECK (INTERACTIVE RUNS ONLY)
# =============================================================================
# Check if Outlook is running before attempting to connect
# Note: Scheduled runs handle Outlook availability gracefully in the connection section below
if ([Environment]::UserInteractive) {
try {
$outlookProcesses = Get-Process -Name "OUTLOOK" -ErrorAction SilentlyContinue
if (-not $outlookProcesses) {
Write-Host "[ERROR] Outlook is not running!" -ForegroundColor Red
Write-Host ""
Write-Host "The archive script requires Outlook to be running to access email data." -ForegroundColor Yellow
Write-Host ""
Write-Host "Please:" -ForegroundColor Cyan
Write-Host "1. Start Outlook manually" -ForegroundColor White
Write-Host "2. Run this script again" -ForegroundColor White
Write-Host "3. Set up a scheduled task that runs when Outlook starts" -ForegroundColor White
Write-Host ""
Write-Host "Press any key to exit..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
exit 1
}
Write-Host "[OK] Outlook is running. Proceeding with archive process..." -ForegroundColor Green
}
catch {
Write-Host "[!] Could not check Outlook status. Proceeding anyway..." -ForegroundColor Yellow
}
}
# =============================================================================
# LOGGING SYSTEM SETUP
# =============================================================================
# Initialize logging system for tracking archive operations
# Logs are essential for troubleshooting and audit trails
$LogFile = $null
try {
# Ensure LogPath is valid before attempting to create log files
if ([string]::IsNullOrEmpty($LogPath)) {
throw "LogPath is null or empty"
}
# Create log directory if it doesn't exist
if (-not (Test-Path $LogPath)) {
New-Item -Path $LogPath -ItemType Directory -Force -ErrorAction Stop | Out-Null
Write-Host "Created log directory: $LogPath"
}
# Create log file path with timestamp for uniqueness
$LogFile = Join-Path $LogPath ("ArchiveLog_" + $Today.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt")
# Initialize log file with header information
"=== Outlook Auto-Archive Dry-Run ===" | Out-File -FilePath $LogFile -Encoding UTF8
"Retention: $RetentionDays days" | Out-File -FilePath $LogFile -Append -Encoding UTF8
"Cutoff: $CutOff" | Out-File -FilePath $LogFile -Append -Encoding UTF8
Write-Host "Logging initialized successfully: $LogFile"
}
catch {
Write-Host "Error setting up logging: $_" -ForegroundColor Red
Write-Host "LogPath: $LogPath" -ForegroundColor Yellow
Write-Host "Continuing without logging..." -ForegroundColor Yellow
$LogFile = $null
}
# =============================================================================
# OUTLOOK CONNECTION FOR MAIN PROCESSING
# =============================================================================
# Establish connection to Outlook for the main archiving process
# This handles both interactive and scheduled runs with appropriate error handling
if (-not $outlook -or -not $namespace) {
try {
$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNamespace("MAPI")
Write-Host "[OK] Connected to Outlook for processing" -ForegroundColor Green
}
catch {
# Check if this is a scheduled run (non-interactive)
$isScheduledRun = $false
try {
# Check if we're running from Task Scheduler (non-interactive environment)
$isScheduledRun = -not [Environment]::UserInteractive -or $null -eq $env:COMPUTERNAME
}
catch {
# If we can't determine, assume it might be scheduled
$isScheduledRun = $true
}
if ($isScheduledRun) {
# Graceful handling for scheduled runs
$logMessage = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] Outlook is not running. Skipping scheduled archive run."
Write-Host $logMessage -ForegroundColor Yellow
# Try to log to file if possible
if ($LogFile -and (Test-Path (Split-Path $LogFile -Parent))) {
try {
$logMessage | Out-File -FilePath $LogFile -Append -Encoding UTF8 -ErrorAction SilentlyContinue
}
catch {
# Silently continue if logging fails
}
}
# Exit gracefully with success code for scheduled tasks
exit 0
}
else {
# Interactive run - show error and exit with failure
Write-Host "[ERROR] Failed to connect to Outlook: $_" -ForegroundColor Red
Write-Host "Make sure Outlook is running and you have the necessary permissions." -ForegroundColor Yellow
exit 1
}
}
}
# =============================================================================
# HELPER FUNCTIONS
# =============================================================================
# =============================================================================
# HELPER FUNCTIONS
# =============================================================================
# Helper function for safe logging to both console and file
# This ensures consistent logging behavior throughout the script
function Write-Log {
param(
[string]$Message, # Message to log
[string]$LogFile # Path to log file (optional)
)