-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLaunch-eDiscoveryGUI.ps1
2163 lines (2033 loc) · 102 KB
/
Launch-eDiscoveryGUI.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
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
<#
.NOTES
Needed a Graphical User Interface for eDiscovery tasks, for both Search-mailbox and New-MailboxSearch.
Needed a way to track search progress for New-MailboxSearch
BIG THANKS TO PRATEEK SINGH
His script gave be the base for this application:
Based this tool on a script from the great Prateek Singh : http://en.gravatar.com/almostit - great guy !
And the page of his script is here:
https://geekeefy.wordpress.com/2016/02/26/powershell-gui-based-email-search-and-removal-in-exchange/
I developped around it to include:
- Bilingual Graphical Interface (logging in a file is still in English)
- Added the code for New-MailboxSearch and related options in addition to Search-Mailbox
- Powershell Cmdlet generator: as we click and type, we see the generation of the corresponding Powershell code
- Added the option to estimate only the search
- Added multiple tabs to include
- Connection button to Exchange Online or On-Premise environment
- Exchange rights status displayed on the tool for the currently logged on user: Exchange Discovery Management + Exchange Import Export
- Tabs that leverage Get-MailboxSearch, and permits to remove previous New-MailboxSearch generated searches
Credits for the Logging function goes to SAM BOUTROS
https://social.technet.microsoft.com/Profile/sam%20boutros
Initial link for the Log function here:
https://gallery.technet.microsoft.com/scriptcenter/Scriptfunction-to-display-7f7f36a9
.DESCRIPTION
IMPORTANT - This script requires Exchange 201X commandlets - which you get either by clicking on the "Connect to Exchange" button, or by launching this script from an Exchange Management Shell.
Exchange Management Shell is actually a powershell console that we open, and inside which we launch a couple of command lines which effect is to connect to the Exchange environment, and to import additional commands that enable you to manage Exchange with the command line (like "Get-Mailbox" which will give you a list of mailboxes, "Search-Mailbox", "New-MailboxSearch", etc....)
This script is a GUI wrapper that launches Powershell commands: it pops up a Windows dialog box with a tabs, and from where you can launch the Mailbox Search cmdlets (Search-Mailbox, New-MailboxSearch) just with the click of a button – after having populated the things you wish to search (dates, keywords, mailboxes to search, etc...).
So normally, you won’t have to mess up with Powershell commands, even if the script outputs some of these – it’s just if you want to use Powershell if you’re curious about it
NOTE: To remove the "Connect to Exchange" button, just comment the .Controls.Add() control on the tabPage0 configuration section
Release notes:
==============
1- Complete version, GUI bilingual French/English (Powershell underlying console in English), switch to connect to On-Premise or O365 Exchange
1.1 - Added a check on Search-Mailbox -DeleteContent parameter and grey out "Delete Mailbox" if we don't have the right to Delete
1.2 - normalized strings
1.3 - Added test on Discovery Mailbox - if it doesn't exist, inform the user - except for Search-Mailbox -EstimateOnly, which doesn't need a Discovery Mailbox.
1.401 - added and optimized the Welcome/Readme text in English and French
Fix: removed Get-Credentials -Message as the "-Message" parameter doesn't work on Powershell v2.0 (Windows 2008 R2 Powershell).
1.402 - removed "check spelling of Discovery mailbox" when error when one mailbox is not found. Discovery Mailbox check is done separately
1.5 - Added logging into a file
LOG File is always created under User's profile \ Documents folder. Log file name hard coded (search for string:
"$($env:userprofile)\Documents\eDiscoveryLog.txt"
Can always change the log file destination by using the "-LogFile" parameter after each call of the "Log" function
1.5.1 - case Source Mailboxes to search in is blank
Updated Update-CmdLine when SourceMailboxes is blank
Add confirmation to continue searching all mailboxes (Continue ? Yes/No)
Updated btn_Run function -> using the command line built by Update-CmdLine function (reusing $richTextBox.Text) - NOTE: btn_Run has additionnal tests
1.5.2 - FR and US translation for "search in all mailboxes" confirm box.
1.5.3 - added filter on Get-mailbox to exclude search in Discovery Mailbox when using Search-Mailbox
1.5.4 - fixed Right to Delete variable $RightToDelete - was set in the Test-ExchCx function but was local to
this function only. Fix : make it global for the whole application.
1.5.4.1 - 09 MAR 2017 - changed a bit the Log function to add default string in case no String parameter is specified
1.5.4.2 - 09 MAR 2017 - removed the "-LogLevel full" if "-DeleteContent" is checked...
1.5.5 - Review code and remove a few useless comments before publishing
1.5.6 - Adding suggestions (no code modification) - Publishing version
18AUG2017 - incrementing minor version to get rid of minor-minor version
Suggestion : add time in date selection for searches.
1.5.6.1 - fixing Get-Mailbox -REsultSize Unlimited | Search-Mailbox / changing to Get-MailboxDatabase | ForEach {Get-Mailbox $_ -resultsize Unlmited | Search-Mailbox blablablabla}
1.5.7 - Change to Delete e-mails option using Search-Mailbox : instead of loading all mailboxes of an Org and piping all on Search-Mailbox,
I load all MAilboxDatabases first, and using ForEach ($Database in $DatabaseList) {$MBXBatch = Get-Mailbox -Database $Database; and piping $MBXBatch to Search-Mailbox instead.
1.5.7.1 - Encoding issue - re-saved the file with UTF-8 encoding - French accents were messing up with the whole script
1.6 - REplaced legacy Exchange Online connection function with modern Exchange Online Management V2 connection function (Connect-ExchOnlineV2)
Also fixed a DiscoveryMailbox test logic issue (didn't update progress bar label in case DiscoverMailbox does not exist + output message didn't make sense at all - bruh what was I thinking ?? )
1.7 - changed SearchQuery "" to SearchQuery {} (curly brackets instead of double quotes for SearchQuery)
1.7.1 - fixed From/Attachments/Keywords string generation issue
Intention for vNext:
- remove first occurrence in SearchQuery if no keywords specified
- Add CSV file picker to choose .CSV file as input for list of mailboxes to search in
Would also like to add function to test if each mailbox in the list exist before launching the search
- Add date picker, and if no date selected, remove date filters in Search-Mailbox and New-MailboxSearch generated command lines
- Use -Force for Search-Mailbox instead of -Confirm $false which is not taken into account (Search-Mailbox with
"-DeleteContent" continues to prompt for deletions when using Get-Mailbox | Search-Mailbox...
#>
#Switch the $TestMode variable to $true for tool testing, and to $false when finished testing
$TestMode = $true
$OrganizationNameEN = "Microsoft Exchange Search"
$OrganizationNameFR = "Recherche Microsoft Exchange"
$CurrentVersion = "1.7"
#------------------------------------------------
#region Application Functions
#------------------------------------------------
Function Split-ListSemicolon
{
param(
[string]$StringToSplit
)
$TargetEmailSplit = $StringToSplit.Split(';')
$SourceMailboxes = ""
For ($i = 0; $i -lt $TargetEmailSplit.Count - 1; $i++) {$SourceMailboxes += ("""") + $TargetEmailSplit[$i] + (""",")}
$SourceMailboxes += ("""") + $TargetEmailSplit[$TargetEmailSplit.Count - 1] + ("""")
Return $SourceMailboxes
}
Function Validate-Mailboxes ($Mailboxes)
{
# Placeholder function for future version .... test existence of mailboxes before launching the search function
# (can save time ... have to test)
}
function Log
{
<#
.Synopsis
Function to log input string to file and display it to screen
.Description
Function to log input string to file and display it to screen. Log entries in the log file are time stamped. Function allows for displaying text to screen in different colors.
.Parameter String
The string to be displayed to the screen and saved to the log file
.Parameter Color
The color in which to display the input string on the screen
Default is White
Valid options are
Black
Blue
Cyan
DarkBlue
DarkCyan
DarkGray
DarkGreen
DarkMagenta
DarkRed
DarkYellow
Gray
Green
Magenta
Red
White
Yellow
.Parameter LogFile
Path to the file where the input string should be saved.
Example: c:\log.txt
If absent, the input string will be displayed to the screen only and not saved to log file
.Example
Log -String "Hello World" -Color Yellow -LogFile c:\log.txt
This example displays the "Hello World" string to the console in yellow, and adds it as a new line to the file c:\log.txt
If c:\log.txt does not exist it will be created.
Log entries in the log file are time stamped. Sample output:
2014.08.06 06:52:17 AM: Hello World
.Example
Log "$((Get-Location).Path)" Cyan
This example displays current path in Cyan, and does not log the displayed text to log file.
.Example
"$((Get-Process | select -First 1).name) process ID is $((Get-Process | select -First 1).id)" | log -color DarkYellow
Sample output of this example:
"MDM process ID is 4492" in dark yellow
.Example
log "Found",(Get-ChildItem -Path .\ -File).Count,"files in folder",(Get-Item .\).FullName Green,Yellow,Green,Cyan .\mylog.txt
Sample output will look like:
Found 520 files in folder D:\Sandbox - and will have the listed foreground colors
.Link
https://superwidgets.wordpress.com/category/powershell/
.Notes
Function by Sam Boutros
v1.0 - 08/06/2014
v1.1 - 12/01/2014 - added multi-color display in the same line
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')]
Param(
[Parameter(Mandatory = $true,
ValueFromPipeLine = $true,
ValueFromPipeLineByPropertyName = $true,
Position = 0)]
[AllowNull()]
# added default "No Log Specified"
[String[]]$String = "No Log Specified",
[Parameter(Mandatory = $false,
Position = 1)]
[ValidateSet("Black", "Blue", "Cyan", "DarkBlue", "DarkCyan", "DarkGray", "DarkGreen", "DarkMagenta", "DarkRed", "DarkYellow", "Gray", "Green", "Magenta", "Red", "White", "Yellow")]
[String[]]$Color = "DarkGreen",
[Parameter(Mandatory = $false,
Position = 2)]
[String]$LogFile = "$($env:userprofile)\Documents\eDiscoveryLog.txt",
[Parameter(Mandatory = $false,
Position = 3)]
[Switch]$NoNewLine
)
if ($String.Count -gt 1)
{
$i = 0
foreach ($item in $String)
{
if (($item -eq $null) -or ($item -eq "")) { $item = 'null' }
if ($Color[$i]) { $col = $Color[$i] } else { $col = "White" }
Write-Host "$item " -ForegroundColor $col -NoNewline
$i++
}
if (-not ($NoNewLine)) { Write-Host " " }
}
else
{
if ($NoNewLine) { Write-Host $String -ForegroundColor $Color[0] -NoNewline }
else { Write-Host $String -ForegroundColor $Color[0] }
}
if ($LogFile.Length -gt 2)
{
"$(Get-Date -format "yyyy.MM.dd hh:mm:ss tt"): $($String -join " ")" | Out-File -Filepath $Logfile -Append
}
else
{
Write-Verbose "Log: Missing -LogFile parameter. Will not save input string to log file.."
}
}
#------------------------------------------------
#endregion Application Functions
#------------------------------------------------
#------------------------------------------------
# Form Function - This is the main tool
#------------------------------------------------
function Search-MailboxGUI
{
#Parameters - only language selection in this case
param(
[Parameter(Mandatory = $True, Position = 1)]
[string]$language
)
#------------------------------------------------
#region ########### Manage the locale strings here ! ################
#------------------------------------------------
Switch ($language)
{
"EN"
{
#region Locale = EN
#Menus, buttons, labels ...
$Str000 = "eDiscovery Tool"
$Str001 = "Welcome !"
$Str002 = "$OrganizationNameEN"
$Str003 = "Exchange 2010, 2013, 2016, Exchange Online"
$Str004 = "Ready !"
$Str004a = "Please wait while working..."
$Str004b = "Please wait while closing existing sessions ..."
$Str005 = "Connect to Exchange"
$Str006 = "Connection Status:"
$Str007 = "Not Connected to Exchange"
$Str007a = "Connected to Exchange"
$Str007b = "Able to search !"
$Str007c = "Discovery Rights not present !"
$Str007d = "Connecting..."
$Str007e = "Can delete mails from source."
$Str007f = "Cannot delete mails from source."
$Str008 = "Search in mailboxes"
$Str009 = "Recipient E-mail, separated by semi-colons:"
$Str010 = "Sender E-mail"
$Str011 = "Attachment name"
$Str012 = "Search Keyword"
$Str013 = "Search Only in Subject Line"
$Str014 = "Start Date (MM/DD/YYYY)"
$Str015 = "End Date (MM/DD/YYYY)"
$Str016 = "Delete E-mail from Source ? NOTE: 'Mailbox Import Export' right required"
$Str017 = "Search a bit quicker using New-MailboxSearch (cannot delete mail)"
$Str018 = "Estimate only (don't store results)"
$Str019 = "Mailbox to store E-mails in:"
$Str020 = "Folder:"
$Str021 = "Launch Search"
$Str022 = "Close the tool"
$Str023 = "Retrieve Mailbox Searches"
$Str024 = "This area is there to be able to request and view existing searches launched with the ""New-MailboxSearch"" option checked..."
$Str025 = "Get previous mailbox search"
$Str026 = "Get ALL mailbox searches"
$Txt002 = "Working to get mailbox search"
$Txt002a = "defined on tab ""Search In Mailboxes"" please wait..."
$Txt002b = "Working to get ALL mailbox searches still on the system, please wait..."
$Txt003 = "Cannot find any search named"
$Txt003a = "... try another ""Folder:"" name on the ""Search Mailbox"" tab, or click on ""Get ALL mailbox searches..."" button."
$TxtLbl001 = "Name"
$TxtLbl002 = "% Progress"
$TxtLbl003 = "Nb findings"
$Str027 = "Retrieve Mailbox Searches Statistics"
$Str028 = "Populate or update drop down list"
$Str029 = "Click the below link to go to the mailbox where the results are stored:"
$Str029a = "Click the below link to fo to the mailbox ("
$Str029b = ") where the results are stored for"
$Str030 = "Results Link"
$Txt005 = "Please click on the ""Populate or update drop down list"" button to begin retrieving statistics about previousliy run Mailbox Searches (NOTE: only previous searches done with ""New-MailboxSearch"" are displayed)"
$Txt006 = "Working on getting Mailbox Search names currently on the system..."
$Txt007 = "Found"
$Txt007a = "searches on the system !"
$Txt008 = "Use the drop down list above to get more statistical information about a particular Mailbox Search !"
$Txt009 = "Please wait, we're gathering the mailbox search statistics..."
$Txt010 = "Showing the search statistics for"
$Txt011 = "No mailbox searches found ... do some and come back later on this tab !"
$Txt012 = "No link for this search. Probably an estimate."
$Txt013 = "No valid link for this search..."
$Txt014 = "Search interface terminated."
$Err001 = "An error occurred - most likely one of the mailboxes doesn't exist or the there is a typo in one of the mailboxes name or address..."
$Err002 = "A Mailbox Search with the same name already exists. Please type another one in the ""Folder"" field of the GUI on the ""Research Mailboxes"" tab...`nor remove the existing mailbox search, and run the script again..."
$Err003 = "Wrong creds or no creds entered ..."
$Str031 = "Do you really want to remove that MailboxSearch ?"
$Str032 = "not deleted, returning to the search tool..."
$Txt015 = "Deleting selected mailbox search, please wait..."
$Str033 = "was deleted !"
$Str034 = "On-Premise Exchange"
$Str035 = "O365 Exchange"
$Err004 = "On-Premise Exchange connection failed - wrong credentials or server URL connection... please try again or connect to an O365 Exchange environment."
$Txt001 = "Welcome to the eDiscovery Graphical Interface tool.`n`nHere is a quick description of the tabs:`n`n`n1- the ""$Str001"" tab`n=================================================`n>> it's this tab.`n`nConnect to Exchange Online or to Exchange on-premise. You will also see the status of your Powershell session:`n- ""$Str007""`n--->if you are not in a Powershell session with Exchange cmdlets`n- ""$Str007a""`n--->if you are in a Powershell session with Exchange cmdlets`n- ""$Str007b""`n--->if you have the rights to execute the ""Search-Mailbox"" and the ""New-MailboxSearch"" cmdlets, which are required to use this tool`n- ""$Str007c""`n--->if you don't have the ""Search-Mailbox"" and the ""New-MailboxSearch"" rights brought by the ""Discovery Management"" RBAC role`n- ""$Str007d""`n--->when you are importing an Exchange Powershell session O365 or Exchange on-premise`n- ""$Str007e""`n--->if you have the ""Mailbox Import Export"" rights which are required to be able to remove e-mails searched`n- ""$Str007f""`n--->if you don't have the ""Mailbox Import Export"" rights`n`n2- the ""$Str008"" tab`n=================================================`n>> it's the tab where you search, estimate searches, or purge searched e-mails from mailboxes (malicious, sensitive, ...)`n`n> This tab provides the Powershell cmdlet that correspond to the search options and parameters filled. This cmdlet is automatically generated, in real time. You can either launch the search using the ""$Str021"" button, or just copy and paste the generated cmdlet on another Exchange Powershell session.`n> Also, this tab enabled you to choose whether you prefer to use Search-Mailbox or New-MailboxSearch to perform your search.`n*** NOTE1: Search-Mailbox has an option to purge the source mailbox, while New-MailboxSearch is read-only.`n*** NOTE2: Also note that New-MailboxSearch keep the searches statistics on the Exchange server, while Search-Mailbox doesn't.`nHowever, both cmdlets also store their search results on the Discovery Mailbox (except Search-Mailbox -EstimateOnly) – New-MailboxSearch also stores the search results statistics on the Exchange servers, as well as on the Discovery Mailbox.`n`n3- the ""$Str023"" tab`n==================================================`n>> it's the tab where you can followup with the Search status of the mailboxes.`n*** NOTE: searches performed with ""New-MailboxSearch"" cmdlet are performed on the remote Exchange server, and you don't see the search progress right away. You have to use this tab.`n`n4- the ""$Str027"" tab`n==================================================`n>> this tab enables you to view more detailed search statistics for searches performed with ""New-MailboxSearch"". `n`nThis tab also provides you with the ability to:`n> Access the Discovery Mailbox directly by a provided URL, which updates upon the selected Mailbox Search`n> Delete previous searches, including the results stored in the corresponding Discovery Mailbox`n`nEnjoy this tool !"
$Err005 = "The discovery mailbox for storing search results and statistics does not exist - please put an existing name or E-mail address for a discovery mailbox which you have access to."
$Str036 = "No e-mail addresses specified => will scan all mailboxes, do you want to continue ?"
#endregion Locale = EN
}
"FR"
{
#region Locale = FR
$Str000 = "Outil de recherche"
$Str001 = "Bienvenue !"
$Str002 = "$OrganizationNameFR"
$Str003 = "Exchange 2010, 2013, 2016, Exchange en-ligne"
$Str004 = "Prêt !"
$Str004a = "Veuillez patienter, opération en cours..."
$Str004b = "Veuillez patienter pendant la fermeture des sessions existentes..."
$Str005 = "Se connecter à Exchange"
$Str006 = "Statut de connexion:"
$Str007 = "Non connecté à Exchange"
$Str007a = "Connecté à Exchange"
$Str007b = "Vous avez les droits de recherche !"
$Str007c = "Vous n'avez pas les droits de recherche."
$Str007d = "Connexion en cours..."
$Str007e = "Vous avez les droits de suppression de courriels."
$Str007f = "Vous ne pouvez pas supprimer de courriels."
$Str008 = "Rechercher dans les boîtes aux lettres"
$Str009 = "Adresses courriel, séparées par des point-virgules:"
$Str010 = "Adresse de l'expéditeur"
$Str011 = "Nom de pièce jointe"
$Str012 = "Mot-clé de recherche"
$Str013 = "Rechercher dans le sujet seulement"
$Str014 = "Date de début (MM/JJ/AAAA)"
$Str015 = "Date de fin (MM/JJ/AAAA)"
$Str016 = "Supprimer le courriel de la boîte aux lettres ? NOTE: la permission 'Mailbox Import Export' est requise"
$Str017 = "Rechercher plus rapidement avec New-MailboxSearch (ne peut supprimer de courriel)"
$Str018 = "Estimer seulement (ne pas stocker les résultats)"
$Str019 = "Boîte aux lettres de résultats:"
$Str020 = "Répertoire:"
$Str021 = "Lancer la recherche"
$Str022 = "Fermer l'outil"
$Str023 = "Retrouver les recherches précédentes"
$Str024 = "Cette partie de l'outil permet le contrôle de l'état de la dernière recherche effectuée ainsi que de toutes les dernières recherches effectuées à l'aide de l'option ""New-MailboxSearch""..."
$Str025 = "Afficher recherche précédente"
$Str026 = "Afficher TOUTES les recherches"
$Txt002 = "Récupération de la recherche"
$Txt002a = "définie dans l'onglet ""Recherche dans les boîtes aux lettres"", veuillez patienter..."
$Txt002b = "Récupération des données d'état de TOUTES les recherches disponibles dans le système, veuillez patienter..."
$Txt003 = "Impossible de trouver une recherche nommée"
$Txt003a = "... essayez un autre nom de ""Répertoire"" dans l'onglet ""Recherche dans les boîtes aux lettres"", ou cliquer sur le bouton ""Afficher TOUTES les recherches""."
$TxtLbl001 = "Nom"
$TxtLbl002 = "% Progression"
$TxtLbl003 = "Nb résultats"
$Str027 = "Statistiques des recherches"
$Str028 = "Mettre à jour liste déroulante"
$Str029 = "Clicker sur le lien ci-dessous pour ouvrir la boite aux lettres où sont stockés les résultats de la recherche:"
$Str029a = "Clicker sur le lien ci-dessous pour ouvrir la boite ("
$Str029b = ") dans laquelle les résultats sont stockés pour"
$Str030 = "Lien vers la boîte aux lettres des résultats"
$Txt005 = "Veuillez clicker sur le bouton ""Mettre à jour liste déroulante"" pour commencer à retrouver les statistiques des recherches précédentes (NOTE: seules les recherches effectuées à l'aide de ""New-MailboxSearch"" sont affichées)"
$Txt006 = "Recherche des précédentes recherches actuellement dans le système..."
$Txt007 = "On a trouvé"
$Txt007a = "recherches sur le système !"
$Txt008 = "Utilisez la liste déroulante ci-dessus afin de récupérer les statistiques détaillées sur une recherche en particulier !"
$Txt009 = "Veuillez patienter, nous récupérons les statistiques de recherches ..."
$Txt010 = "Statistiques trouvées pour"
$Txt011 = "Aucune recherche trouvée ... faites quelques recherches puis revenez plus tard dans cet onglet !"
$Txt012 = "Aucun lien disponible pout cette recherche... il s'agit probablement d'une recherche avec ""Estimation"" seulement."
$Txt013 = "Pas de lien valide pour cette recherche..."
$Txt014 = "Interface de recherche fermée."
$Err001 = "Une erreur est survenue - il se peut que l'une des boîtes aux lettres n'existe pas ou qu'il y ait une faute de frappe dans l'adresse courriel ou le nom de l'une des boîtes recherchées... "
$Err002 = "Une recherche de boîtes aux lettres portant le même nom existe déjà. Veuillez utiliser un autre nom dans le champ ""Répertoire:"" de l'onglet ""Recherche...""...`nou veuillez supprimer la recherche du même nom puis réessayez la recherche à nouveau..."
$Err003 = "Mauvais compte et/ou mot de passe entrés ..."
$Str031 = "Voulez-vous vraiment supprimer cette recherche ?"
$Str032 = "pas supprimée, retour à l'outil de recherche..."
$Txt015 = "Suppression de la recherche sélectionnée, veuillez patienter..."
$Str033 = "a été supprimée !"
$Str034 = "Exchange privé ou local"
$Str035 = "Exchange O365"
$Err004 = "Erreur de connexion à un environnement Exchange privé - mauvais login&mot de passe ou mauvaise URL de connexion... veuillez ré-essayer ou connectez-vous à un environnement O365 Exchange."
$Txt001 = "Bienvenue dans l’application de recherche de courriel.`n`nVoici une description rapide des onglets :`n`n`n1- Onglet ""$Str001""`n=================================================`n>> vous y êtes.`n`nConnectez-vous à Exchange en-ligne (O365) ou à une infrastructure Exchange locale. Vous verrez le statut de votre session Powershell:`n- ""$Str007""`n-----> Aucune commande Exchange n’est disponible`n- ""$Str007a""`n-----> Les commandes principales Exchange sont disponibles`n- ""$Str007b""`n-----> En plus d’avoir les commandes Exchanges, vous avez accès aux commandes de recherche (nécessite les droits ""Search-Mailbox"" et ""New-MailboxSearch"" conférés par le rôle RBAC ""Discovery Management"")`n- ""$Str007c""`n-----> Vous avez les commandes Exchange disponibles, mais vous n’avez pas de droits de recherche`n- ""$Str007d""`n-----> L’outil est en cours de tentative de connextion à un environnement Exchange`n- ""$Str007e""`n-----> Vous avez les droits de suppression de mails à l’aide des commandes de recherche ! (Droits ""Mailbox Import Export"")`n- ""$Str007f""`n-----> Vous n’avez pas les droits de suppression de mails conférés par le rôle d’administration ""Mailbox Import Export""`n`n2- Onglet ""$Str008""`n=================================================`n>> onglet de recherche, estimations, ou purge de courriels recherchés (malicieux, sensibles, ...)`n`n> cet onglet génère en temps réel la ligne de commande Powershell complète. Vous pouvez lancer une recherche directement depuis l’interface avec le bouton ""$Str021"" ou simplement copier et coller la ligne de commande générée par l’application dans une nouvelle fenêtre Powershell ou Exchange Management Shell.`n> vous pouvez choisir d’utiliser soit la méthode ""New-MailboxSearch"" (activée par défaut), soit la méthode ""Search-Mailbox"".`n*** NOTE1 : ""Search-Mailbox"" est la seule méthode permettant de purger une boîte de certains messages, alors que ""New-MailboxSearch"" est une méthode de recherche en lecture seule.`n*** NOTE2 : les deux commandes enregistrent leurs résultats de recherche dans une boîte aux lettres de découverte (sauf Search-Mailbox -EstimateOnly) - ""New-MailboxSearch"" sauvegarde également les statistiques de recherches sur le serveur Exchange ainsi que dans la boîte de recherche.`n`n3- Onglet ""$Str023""`n=================================================`n>> permet de suivre la progression des recherches effectuées à l’aide de ""New-MailboxSearch"".`n*** NOTE : ""New-MailboxSearch"" envoie une demande de recherche dans une file d’attente au niveau des serveurs Exchange. Cet onglet permet de suivre et d’afficher le statut et les statistiques de ces recherches.`n`n4- Onglet ""$Str027""`n=================================================`n>> permet d’afficher les détails des recherches effectuées à l’aide de ""New-MailboxSearch""`nCet onglet permet également :`n> le lancement d’une session Outlook Web App pour l’accès à la boîte de découverte utilisée pour la recherche dont vous avez affiché les informations.`n> la suppression de recherches précédentes, incluant les résultats de ces recherches stockés dans la boîte de recherche correspondante.`n`nBonnes recherches !"
$Err005 = "La boîte aux lettre de découverte pour le stockage des résultats et statistiques de recherches n'existe pas - veuillez mettre un nom de boîte aux lettres de découverte qui existe et à laquelle vous avez accès..."
$Str036 = "Aucune addresse e-mail spécifiée => recherche dans toutes les boîtes aux lettres, on continue ?"
#endregion Locale FR
}
}
$Str000 += " - v" + $CurrentVersion
Log "***********************************************************************************"
Log "Search Tool $Str000 Welcome !"
Log "Logging Started"
Log "***********************************************************************************"
#------------------------------------------------
#endregion ########### Manage the locale strings here ! ################
#------------------------------------------------
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
#----------------------------------------------
#endregion Import Assemblies
#------------------------------------------------
#----------------------------------------------
#region Form Objects and Elements Instantiation
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
##Form object instantiation
$frmSearchForm = New-Object 'System.Windows.Forms.Form'
## Error Box message
$MsgBoxError = [System.Windows.Forms.MessageBox]
##tabbing - step 1 - create Tab Control object to put in the form, and also the Tab Pages objects to put in Tab Control later on
##Tab Control object instantiation - it's the Binder for the tabs
$tabcontrol = New-Object 'System.Windows.Forms.TabControl'
##Tab pages instantiation - these are the Tabs we put in the Binder=tab control
$tabPage0 = New-Object 'System.Windows.Forms.TabPage'
$tabPage1 = New-Object 'System.Windows.Forms.TabPage'
$tabPage2 = New-Object 'System.Windows.Forms.TabPage'
$tabPage3 = New-Object 'System.Windows.Forms.TabPage'
####Tab 0 items - Title, Subtitle, text box to put some welcome text####
$lblabout = New-Object System.Windows.Forms.Label
$lblBigTitle2 = New-Object System.Windows.Forms.Label
$lblBigTitle1 = New-Object System.Windows.Forms.Label
$richtxtWelcome = New-Object System.Windows.Forms.RichTextBox
$btnTab0ConnectExch = New-Object System.Windows.Forms.Button
$lblTab0CxStatus = New-Object System.Windows.Forms.Label
$lblTab0CxStatusUpdate = New-Object System.Windows.Forms.Label
$txtTab0ConnectionURI = New-Object System.Windows.Forms.TextBox
$lblSwitchOnPremOnCloud = New-Object System.Windows.Forms.Label
$chkOnPrem = New-Object System.Windows.Forms.CheckBox
####Tab 1 items####
$txtAttachment = New-Object 'System.Windows.Forms.TextBox'
$chkAttachment = New-Object 'System.Windows.Forms.CheckBox'
$btnCancel = New-Object 'System.Windows.Forms.Button'
$btnRun = New-Object 'System.Windows.Forms.Button'
$txtDiscoveryMailbox = New-Object 'System.Windows.Forms.TextBox'
$lblDiscoveryMailbox = New-Object 'System.Windows.Forms.Label'
$txtDiscoveryMailboxFolder = New-Object 'System.Windows.Forms.TextBox'
$lblDiscoveryMailboxFolder = New-Object 'System.Windows.Forms.Label'
$chkDeleteMail = New-Object 'System.Windows.Forms.CheckBox'
$txtEndDate = New-Object 'System.Windows.Forms.TextBox'
$lblEndDate = New-Object 'System.Windows.Forms.Label'
$txtStartDate = New-Object 'System.Windows.Forms.TextBox'
$lblStartDate = New-Object 'System.Windows.Forms.Label'
$chkSubject = New-Object 'System.Windows.Forms.CheckBox'
$lblKeyword = New-Object 'System.Windows.Forms.Label'
$txtKeyword = New-Object 'System.Windows.Forms.TextBox'
$txtSender = New-Object 'System.Windows.Forms.TextBox'
$chkSender = New-Object 'System.Windows.Forms.CheckBox'
$chkUseNewMailboxSearch = New-Object 'System.Windows.Forms.CheckBox'
$txtRecipient = New-Object 'System.Windows.Forms.TextBox'
$lblRecipient = New-Object 'System.Windows.Forms.Label'
$richTxtCurrentCmdlet = New-Object System.Windows.Forms.RichTextBox
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
$chkEstimateOnly = New-Object System.Windows.Forms.CheckBox
$global:RightToDelete = $true
####Tab 2 items####
$lblTab2ExistingSearches = New-Object 'System.Windows.Forms.Label'
$btnTab2GetMbxSearches = New-Object 'System.Windows.Forms.Button'
$btnTab2Get1MbxSearch = New-Object System.Windows.Forms.Button
$richtxtGetMbxSearch = New-Object 'System.Windows.Forms.RichTextBox'
####Tab 3 items####
$lblTab4URL = New-Object System.Windows.Forms.Label
$lblTab4URLLink = New-Object System.Windows.Forms.LinkLabel
$txtTab4MbxSearchStats = New-Object System.Windows.Forms.RichTextBox
$comboTab4MbxSearches = New-Object System.Windows.Forms.ComboBox
$btnTab4PopList = New-Object System.Windows.Forms.Button
$btnDelSearch = New-Object System.Windows.Forms.Button
$StatusBar = New-Object System.Windows.Forms.StatusBar
#----------------------------------------------
#endregion Form Objects Instantiation
#----------------------------------------------
#----------------------------------------------
#region Application Functions using variables defined within the form function
#----------------------------------------------
function Update-CmdLine()
{
$TargetEmail = $txtRecipient.Text
$DiscoveryMailbox = $txtDiscoveryMailbox.Text
$DiscoveryFolder = $txtDiscoveryMailboxFolder.Text
$SenderEmail = $txtSender.Text
$Keyword = ('''') + $txtKeyword.Text + ('''')
$StartDate = $txtStartDate.Text
$EndDate = $txtEndDate.Text
$DateInt = $StartDate + ".." + $EndDate
$richTxtCurrentCmdlet.ForeColor = 'Green'
if ($chkSender.Checked -eq $true)
{
$From = (" AND from:") + ('''') + $txtSender.Text + ('''')
$FromMultiSenders = Split-ListSemicolon($txtSender.Text); $FromMulti = (" -Senders ") + $FromMultiSenders
}
else
{
$From = ""
$FromMulti = ""
}
if ($chkAttachment.Checked -eq $true) {
$chkSubject.Enabled = $false
$txtKeyword.Enabled = $false
$Attachment = ("attachment:") + ('''') + $txtAttachment.Text + ('''')
}
else { $Attachment = ""
$chkSubject.Enabled = $true
$txtKeyword.Enabled = $true
}
if ($chkSubject.Checked -eq $true) { $Keyword = ("Subject:") + $Keyword }
if ([String]::IsNullOrEmpty($($txtKeyword.Text)) -and [String]::IsNullOrEmpty($Attachment)) {
if ([string]::IsNullOrEmpty($From)){
$SearchQuery = "{Received:`"$DateInt`"}"
}Else{
$SearchQuery = "{Received:`"$DateInt`"$From}"
}
$SearchQueryMulti = ""
} Else {
If ([string]::IsNullOrEmpty($From)){
if ([String]::IsNullOrEmpty($Attachment)){
$SearchQuery = ("{") + "$Keyword" + " AND Received:`"$DateInt`"" + ("}")
} else {
$SearchQuery = ("{") + "$Attachment" + " AND Received:`"$DateInt`"" + ("}")
}
} Else {
if ([String]::IsNullOrEmpty($Attachment)){
$SearchQuery = ("{") + "$Keyword$From" + " AND Received:`"$DateInt`"" + ("}")
} else {
$SearchQuery = ("{") + "$Attachment$From" + " AND Received:`"$DateInt`"" + ("}")
}
}
if ([String]::IsNullOrEmpty($Attachment)){
$SearchQueryMulti = ("{") + "$Keyword" + ("}")
} else {
$SearchQueryMulti = ("{") + "$Attachment" + ("}")
}
}
# Introducing $BlankSource boolean -> if no e-mail addresses specified, search all mailboxes
# To search all mailboxes: remove -SourceMailboxes parameters for New-SeachMailbox, and add "Get-Mailboxes" before the Search-Mailbox
if (($TargetEmail -eq "") -or ($TargetEmail -eq $null)) {$BlankSource = $true} else {$BlankSource = $false; $SourceMailboxes = Split-ListSemicolon($TargetEmail)}
If ($chkUseNewMailboxSearch.Checked -eq $true)
{
If ($BlankSource -eq $false)
{
$CommandMulti = "New-MailboxSearch -Name '$DiscoveryFolder' -SourceMailboxes $SourceMailboxes -TargetMailbox '$DiscoveryMailbox' -StartDate '$StartDate' -EndDate '$EndDate' -SearchQuery $SearchQueryMulti -ExcludeDuplicateMessages `$false -ErrorAction Continue" + $FromMulti
}
else # $BlankSource -eq $true
{
$CommandMulti = "New-MailboxSearch -Name '$DiscoveryFolder' -TargetMailbox '$DiscoveryMailbox' -StartDate '$StartDate' -EndDate '$EndDate' -SearchQuery $SearchQueryMulti -ExcludeDuplicateMessages `$false -ErrorAction Continue" + $FromMulti
}
If ($chkEstimateOnly.Checked -eq $true)
{
$CommandMulti += " -EstimateOnly"
}
$richTxtCurrentCmdlet.Text = $CommandMulti
}
Else #If ($chkUseNewMailboxSearch.Checked -eq $false)
{
If ($BlankSource -eq $false)
{
$Command = $SourceMailboxes + (" | ")
}
else
{
# $blankSource -eq $true
$Command = '$AllDatabases = get-MailboxDatabase; ForEach ($DB in $AllDatabases) {$MBXBatch = get-mailbox -ResultSize unlimited -Filter {RecipientTypeDetails -ne "DiscoveryMailbox"} -Database $DB ; $MBXBatch | '
}
If ($chkDeleteMail.Checked -eq $true)
{
$Command += "Search-Mailbox -TargetMailbox '$DiscoveryMailbox' -TargetFolder '$DiscoveryFolder' -SearchQuery $SearchQuery -Verbose -DeleteContent -Confirm:`$false -Force"
If ($BlankSource) {$Command += "}"}
# Update status bar
$StatusBar.Text = $Str004
}
Else # $chkDeleteMail -eq $false
{
If ($chkEstimateOnly.Checked -eq $true)
{
$Command += "Search-Mailbox -SearchQuery $SearchQuery -Verbose -EstimateResultOnly"
If ($BlankSource) {$Command += "}"}
}
Else
{
#chkEstimateOnly -eq $false
$Command += "Search-Mailbox -TargetMailbox '$DiscoveryMailbox' -TargetFolder '$DiscoveryFolder' -LogLevel full -SearchQuery $SearchQuery -Verbose"
If ($BlankSource) {$Command += "}"}
}
}
$richTxtCurrentCmdlet.Text = $Command
}
}
function Populate-DropDownList
{
$btnDelSearch.Enabled = $false
$lblTab4URL.Text = $Str029
$lblTab4URLLink.Text = $Str030
$lblTab4URLLink.Enabled = $false
$StatusBar.Text = $Str004a
$txtTab4MbxSearchStats.Text = $Txt006
Log $Txt006
#region Gather mailbox searches
$ListOfSearchNames = Get-MailboxSearch | Select Name | Out-String
$ListOfSearchNames = $ListOfSearchNames.Split("`n")
$ListOfSearchNamesOffset = @(0) * ($ListOfSearchNames.Count - 6)
For ($i = 3; $i -le ($ListOfSearchNames.Count - 4); $i++)
{
$ListOfSearchNamesOffset[$i - 3] = $ListOfSearchNames[$i].trim()
# For debugging only #Write-Host "Item $i => $($ListOfSearchNames[$i]) -- Offset Item $($i-3) => $($ListOfSearchNamesOffset[$i-3])`n"
}
#endregion gather mailbox searches
If ($ListOfSearchNames.Count -gt 0)
{
$combotab4MbxSearches.Items.Clear()
$comboTab4MbxSearches.Items.AddRange($ListOfSearchNamesOffset)
$LogString = $Txt007 + (" $($ListOfSearchNamesOffset.count) ") + $Txt007a
$txtTab4MbxSearchStats.Text = $LogString
Log $LogString
$txtTab4MbxSearchStats.Text += ("`n`n") + $Txt008
}
Else
{
$txtTab4MbxSearchStats.Text = $Txt011
Log $Txt011
}
$StatusBar.Text = $Str004
}
Function Test-ExchCx()
{
Try
{
Get-command Get-mailbox -ErrorAction Stop
$lblTab0CxStatusUpdate.ForeColor = 'Green'
$lblTab0CxStatusUpdate.Text = $Str007a
Try
{
Get-command Get-MailboxSearch -ErrorAction Stop
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007b
$tabPage1.enabled = $true
$tabPage2.enabled = $true
$tabPage3.enabled = $true
Try
{
Get-Command Search-Mailbox -ParameterName DeleteContent -ErrorAction Stop | Out-Null
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007e
}
Catch
{
$lblTab0CxStatusUpdate.ForeColor = 'Blue'
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007f
$Global:RightToDelete = $false
$chkDeleteMail.Enabled = $false
}
}
Catch [System.SystemException]
{
$lblTab0CxStatusUpdate.ForeColor = 'Orange'
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007c
$tabPage1.enabled = $false
$tabPage2.enabled = $false
$tabPage3.enabled = $false
}
}
Catch [System.SystemException]
{
$lblTab0CxStatusUpdate.ForeColor = 'Red'
$lblTab0CxStatusUpdate.Text = $Str007
$tabPage1.enabled = $false
$tabPage2.enabled = $false
$tabPage3.enabled = $false
}
}
Function Test-ExchCxTest()
{
Try
{
Get-command Get-mailbox -ErrorAction Stop
$lblTab0CxStatusUpdate.ForeColor = 'Green'
$lblTab0CxStatusUpdate.Text = $Str007a
Try
{
Get-command Get-MailboxSearch -ErrorAction Stop
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007b
$tabPage1.enabled = $true
$tabPage2.enabled = $true
$tabPage3.enabled = $true
Try
{
Get-Command Search-Mailbox -ParameterName DeleteContent -ErrorAction Stop | Out-Null
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007e
}
Catch
{
$lblTab0CxStatusUpdate.ForeColor = 'Blue'
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007f
$Global:RightToDelete = $false
# $chkDeleteMail.Enabled = $false
}
}
Catch [System.SystemException]
{
$lblTab0CxStatusUpdate.ForeColor = 'Orange'
$lblTab0CxStatusUpdate.Text += ("`n") + $Str007c
# $tabPage1.enabled = $false
$tabPage2.enabled = $false
$tabPage3.enabled = $false
}
}
Catch [System.SystemException]
{
$lblTab0CxStatusUpdate.ForeColor = 'Red'
$lblTab0CxStatusUpdate.Text = $Str007
# $tabPage1.enabled = $false
$tabPage2.enabled = $false
$tabPage3.enabled = $false
}
}
Function Connect-ExchOnPrem
{
param(
[Parameter( Mandatory = $false)]
[string]$URL = $txtTab0ConnectionURI.text
)
Try
{
# for Powershell v3+ - $Credentials = Get-Credential -Message "Enter your Exchange admin credentials"
# for Powershell v2+ -
$Credentials = Get-Credential
$ExOPSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$URL/PowerShell/ -Authentication Kerberos -Credential $Credentials -ErrorAction Stop
Import-PSSession $ExOPSession
}
Catch
{
Log $Err004 Red
$MsgBoxError::Show($Err004, $Str000, "OK", "Error")
}
}
Function Connect-ExchOnline
{
try
{
$ExchOnlineCred = Get-Credential -ErrorAction Continue
#save previous session - we'll remove it if login successful with new session
$OldSessions = Get-PSSession
#Create remote Powershell session with Exchange Online
$ExchOnlineSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid -Credential $ExchOnlineCred -Authentication Basic -AllowRedirection -ErrorAction SilentlyContinue
#Import the remote PowerShell session
Import-PSSession $ExchOnlineSession -AllowClobber | Out-Null
Log "Ok, you're in !" Green
#Remove previous sessions (and keep the current one)
$OldSessions | Remove-PSSession
}
catch
{
Log $Err003 Red
$MsgBoxError::Show($Err003, $Str000, "OK", "Error")
}
}
Function Connect-ExchOnlineV2
{
try
{
# TO ADD - TRY CATCH TO CHECK IF EXO V2 module is installed
# BOOKMARK
try {import-module ExchangeOnlineManagement -ErrorAction STOP}catch{
Write-host "ExchangeOnlineManagement aka EXO V2 may not be installed..." -ForegroundColor red
Write-host "Install EXO V2 using Install-Module ExchangeOnlineManagement" -ForegroundColor red
}
Connect-ExchangeOnline -ShowProgress $True
Log "Ok, you're in !" Green
}
catch
{
Log $Err003 Red
$MsgBoxError::Show($Err003, $Str000, "OK", "Error")
}
}
#endregion Application Functions using variables from the form
#----------------------------------------------
#----------------------------------------------
#region Events handling (don't forget to add the event on the controls definition Control_Name.add_Click($control_name_Click)
#----------------------------------------------
$frmSearchForm_Load = {
#Action ->
$btnDelSearch.Enabled = $false
$txtSender.Enabled = $false
$chkSender.Checked = $false
$chkOnPrem.Checked = $false
$txtTab0ConnectionURI.Enabled = $chkOnPrem.Checked
#$chkUseNewMailboxSearch.Checked = $false
$txtAttachment.Enabled = $false
$chkAttachment.Checked = $false
#$chkEstimateOnly.Checked = $True
#$chkUseNewMailboxSearch.Checked = $true
Log $Str000 DarkGreen
$txtExchangeDefaultConnectionURI = "email.contoso.ca"
Update-CmdLine
$StatusBar.Text = $Str004a
if ($TestMode -eq $true) { Test-ExchCxTest } Else { Test-ExchCx }
$StatusBar.Text = $Str004
}
$btnTab0ConnectExch_Click = {
$StatusBar.Text = $Str004a
$lblTab0CxStatusUpdate.Text = $Str007d
$lblTab0CxStatusUpdate.Forecolor = 'Red'
IF ($chkOnPrem.Checked)
{
Connect-ExchOnPrem $txtTab0ConnectionURI.text
if ($TestMode -eq $true) { Test-ExchCxTest } Else { Test-ExchCx }
}
Else
{
Connect-ExchOnlineV2
if ($TestMode -eq $true) { Test-ExchCxTest } Else { Test-ExchCx }
}
$StatusBar.Text = $Str004
}
$lblabout_Click = {
switch ($Language)
{
"EN"
{
$systemst = "QXV0aG9yOiBTYW0gRHJleQ0Kc2FtZHJleUBtaWNyb3NvZnQuY29tDQpzYW1teUBob3RtYWlsLmZyDQpNaWNyb3NvZnQgRW`
5naW5lZXIgc2luY2UgT2N0IDE5OTkNCjE5OTktMjAwMDogUHJlc2FsZXMgRW5naW5lZXIgKEZyYW5jZSkNCjIwMDAtMjAwMzogU3VwcG9yd`
CBFbmdpbmVlciAoRnJhbmNlKQ0KMjAwMy0yMDA2OiB2ZXJ5IGZpcnN0IFBGRSBpbiBGcmFuY2UNCjIwMDYtMjAwOTogTUNTIENvbnN1bHRhb`
nQgKEZyYW5jZSkNCjIwMDktMjAxMDogVEFNIChGcmFuY2UpDQoyMDEwLW5vdyA6IENvbnN1bHRhbnQgKENhbmFkYSkNCk11c2ljaWFuLCBjb`
21wb3NlciAoS2V5Ym9hcmQsIEd1aXRhcikNClBsYW5lIHBpbG90IHNpbmNlIDE5OTUNCkZvciBTaGFyZWQgU2VydmljZXMgQ2FuYWRh"
}
"FR"
{
$systemst = "QXV0ZXVyOiBTYW0gRHJleQ0Kc2FtZHJleUBtaWNyb3NvZnQuY29tDQpzYW1teUBob3RtYWlsLmZyDQpJbmfDqW5pZXVyIGNo`
ZXogTWljcm9zb2Z0IGRlcHVpcyBPY3QgMTk5OQ0KMTk5OS0yMDAwOiBJbmfDqW5pZXVyIEF2YW50LVZlbnRlIChGcmFuY2UpDQoyMDAwLTIwMD`
M6IFNww6ljaWFsaXN0ZSBUZWNobmlxdWUgKEZyYW5jZSkNCjIwMDMtMjAwNjogUHJlbWllciBQRkUgZW4gRnJhbmNlDQoyMDA2LTIwMDk6IENv`
bnN1bHRhbnQgTUNTIChGcmFuY2UpDQoyMDA5LTIwMTA6IFJlc3BvbnNhYmxlIFRlY2huaXF1ZSBkZSBDb21wdGUgKEZyYW5jZSkNCjIwMTAtMjA`
xNiA6IENvbnN1bHRhbnQgKENhbmFkYSkNCk11c2ljaWVuLCBjb21wb3NpdGV1ciAoQ2xhdmllciwgR3VpdGFyZSkNCkJyZXZldCBkZSBQaWxvdGU`
gUHJpdsOpIGRlcHVpcyAxOTk1DQpQb3VyIFNlcnZpY2VzIFBhcnRhZ8OpcyBDYW5hZGE="
}
}
$systemst = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($systemst))
$MsgBoxError::Show($systemst, $Str000, "Ok", "Information")
}
$chkOnPrem_CheckedChanged = {
if ($chkOnPrem.Checked) {$lblSwitchOnPremOnCloud.Text = $Str034} Else {$lblSwitchOnPremOnCloud.Text = $Str035}
$txtTab0ConnectionURI.Enabled = $chkOnPrem.Checked
}
$handler_btnRun_Click = {
#cls
if (($txtRecipient.Text -eq "") -or ($txtRecipient.Text -eq $null))
{
$ChoiceBlankMailContinueYN = $MsgBoxError::Show($Str036, $Str000, "YesNo", "Warning")
}
If ($ChoiceBlankMailContinueYN -eq "No")
{
Write-Host "Returning back to GUI ..."
}
Else
{
$StatusBar.Text = $Str004a
#Action ->
#Extracting Main User data into variables
# $TargetEmail = $txtRecipient.Text
$DiscoveryMailbox = $txtDiscoveryMailbox.Text
$DiscoveryFolder = $txtDiscoveryMailboxFolder.Text
# $SenderEmail = $txtSender.Text
# $Keyword = ('''') + $txtKeyword.Text + ('''')
# $StartDate = $txtStartDate.Text
# $EndDate = $txtEndDate.Text
#Using Date interval Powershell notation for Search Query instead of received :> and received :<
# $DateInt = $StartDate + ".." + $EndDate
$Command = $richTxtCurrentCmdlet.Text
#First things first : checking if the Discovery Mailbox exists if it doesn't, then display error message to get an existing one, bypass all the rest of the code below, and return to GUI
$mailboxTest = $null # Initialize $mailboxTest variable (used to test if a mailbox exists)
$DiscoverMailboxTest = $true # Initialize $DiscoverMailboxTest variable (used as a boolean to say if the mailbox exists or not)
If ($TestMode -eq $True) {Write-Host "Test mode, doing Get-Mailbox $DiscoveryMailbox" -BackgroundColor (Get-Random("Blue", "White", "Red")); $MailboxTest = "Dummy Mailbox"}
Else {$mailboxTest = Get-Mailbox $DiscoveryMailbox -ErrorAction SilentlyContinue}
if (($mailboxTest -eq $null) -or ($mailboxTest -eq ""))
{
$DiscoverMailboxTest = $false
}
If ($chkUseNewMailboxSearch.Checked -eq $false)
{
$MustDoDiscoveryMailboxTestSearchMailbox = $false
If ($chkDeleteMail.Checked -eq $true)
{
$MustDoDiscoveryMailboxTestSearchMailbox = $true
}
Else
{
If ($chkEstimateOnly.Checked -eq $true)
{
Log $Command Blue
If ($TestMode) {Write-Host $Command} Else {$output = invoke-expression $Command | Out-String}
Log $output | Select Identity, TargetMailbox, Success, ResultItemscount, ResultItemsSize | Ft
# Update status bar
$StatusBar.Text = $Str004
}
Else
{
# $ChkEstimateOnly.checked -eq $false
$MustDoDiscoveryMailboxTestSearchMailbox = $true
}
}
If ($MustDoDiscoveryMailboxTestSearchMailbox)
{
Log "Does $DiscoveryMailbox exist ? -->", $DiscoverMailboxTest Green, white
If ($DiscoverMailboxTest)
{
Log "$DiscoveryMailbox exists" Green
Log $Command
If ($TestMode) {Write-Host $Command} Else {$output = invoke-expression $Command | Out-String}
Log $output | Select Identity, TargetMailbox, Success, ResultItemscount, ResultItemsSize | Ft
# Update status bar
$StatusBar.Text = $Str004
#$frmSearchForm.Close()
}
Else
{
$StatusBar.Text = $Str004
$MsgBoxError::Show($Err005, $Str000, "Ok", "Error")
}
}
}
Else
{
#chkUserNewMailboxSearch -eq $true
Log "Does $DiscoveryMailbox exist ? -->", $DiscoverMailboxTest Green, White
Log "Discovery Folder is", $DiscoveryFolder Green, white
If ($DiscoverMailboxTest)
{
Log "$DiscoveryMailbox exists, now because we're using New-MailboxSearch we have to check if ""$DiscoveryFolder"" already exists because New-MailboxSearch cannot use an already existing Search name / folder..." Green
#Clearing errors first
$Error.Clear()
#Trying Get-MailboxSearch with name of Discovery Folder...
If ($TestMode) {Write-Host "$DiscoveryFolder test => Get-MailboxSearch '$DiscoveryFolder'"} Else {invoke-expression "Get-MailboxSearch '$DiscoveryFolder'"}
#If there is no error, that means the folder already exist, close form and exit script...
If (($Error.Count -eq 0) -and ($TestMode -eq $false))
{
Log "A Mailbox Search with the same name already exists. Please type another one in the 'Folder' field of the GUI..." DarkRed
Log "or remove the existing mailbox search by typing the following command or using the GUI:" DarkRed
Log "Remove-MailboxSearch ""$DiscoveryFolder""" DarkGreen
Log "and run the script again..." DarkRed
# Message box for displaying error in the GUI