forked from vilega/O365Troubleshooters
-
Notifications
You must be signed in to change notification settings - Fork 1
/
O365Troubleshooters.psm1
2017 lines (1736 loc) · 115 KB
/
O365Troubleshooters.psm1
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
#region Common Script Blocks
# Getting Credentials script block
$Global:UserCredential = {
Write-Host "`nPlease enter Office 365 Global Admin credentials:" -ForegroundColor Cyan
$Global:O365Cred = Get-Credential
}
# Credential Validation block
$Global:CredentialValidation = {
If (!([string]::IsNullOrEmpty($errordescr)) -and !([string]::IsNullOrEmpty($global:error[0]))) {
Write-Host "`nYou are NOT connected succesfully to $Global:banner. Please verify your credentials." -ForegroundColor Yellow
$CurrentDescription = "`"" + $CurrentError + "`""
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
#&$Global:UserCredential
}
}
# Displaying connection status
$Global:DisplayConnect = {
If ($errordescr -ne $null) {
Write-Host "`nYou are NOT connected succesfully to $Global:banner" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description "You are NOT connected succesfully to $Global:banner"
Write-Host "`nThe script will now exit." -ForegroundColor Red
Read-Host
exit
}
else {
Write-Host "`nYou are connected succesfully to $Global:banner" -ForegroundColor Green
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description "You are connected succesfully to $Global:banner"
}
}
# SPO connection script block:
$Global:SPOConnectBlock = {
$Global:Error.Clear();
$Global:banner = "SharePoint Online PowerShell"
$try++
# Import SPS Online PS module
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
# Creating a new SPS Online PS Session
$Global:UrlSharepoint = "https://$DomainHost-admin.sharepoint.com" -replace " " , ""
Connect-SPOService -Url $UrlSharepoint -credential $O365Cred -ErrorVariable errordescr -ErrorAction SilentlyContinue
$CurrentError = $errordescr.message
#Credentials check
&$Global:CredentialValidation
}
#endregion Common Script Blocks
Function Request-Credential {
# Request for new credentials function. In the case of bad username or password or if the credentials needs to be different (connecting to another tenant).
&$Global:UserCredential
}
Function Connect-O365PS {
# Function to connecto to O365 services
# Parameter request and validation
param (
[ValidateSet("Msol", "AzureAd", "AzureAdPreview", "Exo", "ExoBasic", "Exo2", "Eop", "Scc", "AIPService", "Spo", "Sfb", "Teams", "ADSync")][Parameter(Mandatory = $true)]
$O365Service,
[boolean] $requireCredentials = $True
)
$Try = 0
$global:errordesc = $null
$Global:O365Cred = $null
. $script:modulePath\ActionPlans\Connect-ServicesWithTokens.ps1
#region Module Checks
# Azure Module is mandatory
if ((!($global:addTypeAzureAD) -and ("AzureAd" -in $O365Service ))) {
$minimumVersionAzureAD = '2.0.2.16'
$CurrentProperty = "Checking AzureAD Module"
if ((Get-Module azuread -ListAvailable | Where-Object { $_.Version -ge $minimumVersionAzureAD }).count -gt 0) {
$pathModule = split-path ((Get-Module azuread -ListAvailable | Where-Object { $_.Version -ge $minimumVersionAzureAD } | Sort-Object -Property version -Descending)[0]).Path -parent
$path = join-path $pathModule 'Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
try {
Add-Type -Path $path
}
catch {}
$CurrentDescription = "Azure AD Module for Windows PowerShell is installed and version is $(Split-Path $pathModule -Leaf)"
$global:addTypeAzureAD = $true
}
else {
$CurrentDescription = "Azure AD Module for Windows PowerShell is not installed or version is less than $minimumVersionAzureAD. Initiated install from PowerShell Gallery"
Write-Host "`n$CurrentDescription" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
#Uninstall-Module AzureAD -Force -Confirm:$false -ErrorAction SilentlyContinue |Out-Null
Install-Module AzureAD -Force -Confirm:$false -AllowClobber
$pathModule = split-path ((Get-Module azuread -ListAvailable | Where-Object { $_.Version -ge $minimumVersionAzureAD } | Sort-Object -Property version -Descending)[0]).Path -parent
$path = join-path $pathModule 'Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
try {
Add-Type -Path $path -IgnoreWarnings:$true -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
}
catch {}
$CurrentDescription = "Azure AD Module for Windows PowerShell is installed and version is $(Split-Path $pathModule -Leaf)"
$global:addTypeAzureAD = $true
}
}
# Checking if required modules are installed
If ( $O365Service -eq "MSOL") {
$updateMSOL = $false
[version]$minimumVersion = "1.0.8070"
If ((get-module -ListAvailable -Name MSOnline).count -eq 0 ) {
$updateMSOL = $true
}
else {
$updateMSOL = $true
foreach ($version in (get-module -ListAvailable -Name MSOnline).Version) {
if ($version -ge $minimumVersion) {
$updateMSOL = $false
}
}
}
if ($updateMSOL) {
$CurrentProperty = "Checking MSOL Module"
Write-Host "`nMSOL Module for Windows PowerShell is not installed. Initiated install from PowerShell Gallery" -ForegroundColor Red
$CurrentDescription = "MSOL Module for Windows PowerShell is not installed or is less than required version $minimumVersion. Initiated install from PowerShell Gallery"
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
Uninstall-Module MSOnline -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
Install-Module MSOnline -Force -Confirm:$false -AllowClobber
}
}
<# Removed as AzureAD is mandatory for all connections to request manually the token
If ( $O365Service -eq "AzureAD") {
$updateAzureAD = $false
[version]$minimumVersion = "2.0.0.131"
If ((get-module -ListAvailable -Name AzureAD).count -eq 0 )
{
$updateAzureAD = $True
}
else
{
$updateAzureAD = $True
foreach ($version in (get-module -ListAvailable -Name AzureAD).Version)
{
if ($version -ge $minimumVersion)
{
$updateAzureAD = $false
}
}
}
if ($updateAzureAD)
{
$CurrentProperty = "Checking AzureAD Module"
$CurrentDescription = "Azure AD Module for Windows PowerShell is not installed or version is less than $minimumVersion. Initiated install from PowerShell Gallery"
Write-Host "`n$CurrentDescription" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
#Uninstall-Module AzureAD -Force -Confirm:$false -ErrorAction SilentlyContinue |Out-Null
Install-Module AzureAD -Force -Confirm:$false -AllowClobber
}
}
#>
#TODO: need to check if AzureADPreview for sign-in logs
If ( $O365Service -eq "AzureADPreview") {
$updateAzureADPreview = $false
[version]$minimumVersion = "2.0.2.89"
If ((get-module -ListAvailable -Name AzureADPreview).count -eq 0 ) {
$updateAzureADPreview = $True
}
else {
$updateAzureADPreview = $True
foreach ($version in (get-module -ListAvailable -Name AzureADPreview).Version) {
if ($version -ge $minimumVersion) {
$updateAzureADPreview = $false
}
}
}
if ($updateAzureADPreview) {
$CurrentProperty = "Checking AzureADPreview Module"
$CurrentDescription = "AzureADPreview Module is not installed or version is less than $minimumVersion. Initiated install from PowerShell Gallery"
Write-Host "`n$CurrentDescription" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
#Uninstall-Module AzureADPreview -Force -Confirm:$false -ErrorAction SilentlyContinue |Out-Null
Install-Module AzureADPreview -Force -Confirm:$false -AllowClobber
}
}
If ( $O365Service -eq "AIPService") {
If ((Get-Module -ListAvailable -Name AIPService).count -eq 0) {
$CurrentProperty = "Checking AIPService Module"
$CurrentDescription = "AIPService needs to be updated or you have just updated without restarting the PC/laptop. Script will install the AIPService module from PowerShel Gallery"
Write-Host "`n$CurrentDescription" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
Install-Module -Name AIPService -Force -Confirm:$false -AllowClobber
Write-Host "Installed the AIPService module"
#TODO: if AADRM module was installed, that needs to be uninstalled
#TODO: check if AADRM Module was succesfully installed
}
}
# Currently disabled as connection is done based on access token
<#
if ( $O365Service -eq "Exo") {
if ($null -eq ((Get-ChildItem -Path $($env:LOCALAPPDATA + "\Apps\2.0\") -Filter Microsoft.Exchange.Management.ExoPowershellModule.dll -Recurse).FullName | `
Where-Object { $_ -notmatch "_none_" }))
{
Write-Host "You requested to connect to Exchange Online with MFA but you don't have Exchange Online Remote PowerShell Module installed" -ForegroundColor Red
Write-Host "Please check the article https://docs.microsoft.com/en-us/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/mfa-connect-to-exchange-online-powershell?view=exchange-ps" -ForegroundColor Red
Write-Host "The script will now exit" -ForegroundColor Red
Read-Key
Write-Log -function Connect-O365PS -step "Connect to EXO with Modern & MFA" -Description "Required module is not installed."
Disconnect-All
Exit
}
}
#>
if (($O365Service.tolower() -eq "exo2") -or ($O365Service.tolower() -eq "exo") -or ($O365Service.tolower() -eq "scc")) {
if ((Get-Module -ListAvailable -Name ExchangeOnlineManagement).count -eq 0) {
$CurrentProperty = "Checking ExchangeOnlineManagement v2 Module"
$CurrentDescription = "ExchangeOnlineManagement module is not installed. We'll install it to support connectin to Exchange Online Module v2"
write-host "`n$CurrentDescription" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
Install-Module -Name ExchangeOnlineManagement -Force -Confirm:$false -AllowClobber
}
}
# TODO: SPO prerequisites & modern module check
# TODO: SFB prerequisites & modern module check
If ( $O365Service -eq "ADSync") {
If ((Get-Module -ListAvailable -Name ADSync).count -eq 0) {
$CurrentProperty = "Checking ADSync Module"
$CurrentDescription = "This dianostic have to be executed on AAD Connect server to have access to ADSync PowerShell Module"
Write-Host "`n$CurrentDescription" -ForegroundColor Red
write-log -Function "Connect-O365PS" -Step $CurrentProperty -Description $CurrentDescription
Write-Host "The script was not executed from AAD Connect server." -ForegroundColor Red
Write-Host "Returning to the main menu" -ForegroundColor Red
Read-Key
Start-O365TroubleshootersMenu
}
}
if ($requireCredentials) {
#$Global:proxy = Read-Host
if ($null -eq $Global:proxy) {
Write-Host "`nAre you able to access Internet from this location without a Proxy?" -ForegroundColor Cyan
$Global:proxy = get-choice "Yes", "No"
$Global:PSsettings = New-PSSessionOption -SkipRevocationCheck
if ($Global:proxy -eq "n") {
$Global:PSsettings = New-PSSessionOption -ProxyAccessType IEConfig -SkipRevocationCheck
if ($PSVersionTable.PSVersion.Major -eq 7) {
(Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer
#Write-Host "Please input proxy server address (e.g.: http://proxy): " -ForegroundColor Cyan -NoNewline
#$proxyServer = Read-Host
#Write-Host "Please input proxy server port: " -ForegroundColor Cyan -NoNewline
#$proxyPort = Read-Host
$proxyConnection = "http://" + (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer
}
else {
#It doesn't work in PowerShell7
$proxyConnection = ([System.Net.WebProxy]::GetDefaultProxy()).Address.ToString()
}
Invoke-WebRequest -Proxy $proxyConnection -ProxyUseDefaultCredentials https://provisioningapi.microsoftonline.com/provisioningwebservice.svc
}
}
}
#endregion Module Checks
#region Connection scripts region
if ($requireCredentials) {
if ($global:MfaOption -eq 0) {
do {
# use only default modern authentication window (temporary disable manual managed tokens)
#Write-Host "Do your account require MFA to authenticate? (y/n): " -ForegroundColor Cyan -NoNewline
#$mfa = Read-Host
$mfa = "y"
$mfa = $mfa.ToLower()
if ($mfa -eq "y") {
$global:MfaOption = 1
#Write-Host $global:MfaDisclaimer -ForegroundColor Red
$global:userPrincipalName = Get-ValidEmailAddress("UserPrincipalName used to connect to Office 365 Services")
}
if ($mfa -eq "n") {
$global:MfaOption = 2
$global:credentials = Get-Credential -Message "Please input your Office 365 credentials:"
$global:userPrincipalName = $global:credentials.UserName
}
} until (($mfa -eq "y") -or ($mfa -eq "n"))
}
}
switch ($O365Service) {
# Connect to MSOL
"MSOL" {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "MSOL PowerShell"
$CurrentProperty = "Connect MSOL"
if ($global:MfaOption -eq 2) {
if (!(Get-Module MSOnline)) {
Import-Module MSOnline -Global -DisableNameChecking -ErrorAction SilentlyContinue | Out-Null
}
$token = Get-TokenFromCache("AzureGraph")
if ($null -eq $token) {
$token = Get-Token("AzureGraph")
Connect-MsolService -AdGraphAccessToken $token.AccessToken
}
else {
try {
$null = Get-MsolCompanyInformation -ErrorAction Stop
}
catch {
Connect-MsolService -AdGraphAccessToken $token.AccessToken
}
}
}
elseif ($global:MfaOption -eq 1) {
Do {
$errordescr = $null
$try++
try {
$null = Get-MsolCompanyInformation -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("MSOnline" -in (Get-Module).name)) {
Import-Module MSOnline -Global -DisableNameChecking -ErrorAction SilentlyContinue | Out-Null
}
$errordescr = $null
Connect-MsolService -ErrorVariable errordescr -ErrorAction SilentlyContinue
if ($null -eq $Global:Domain) {
$Global:Domain = (get-msoldomain -ErrorAction SilentlyContinue -ErrorVariable errordescr | Where-Object { $_.name -like "*.onmicrosoft.com" } | Where-Object { $_.name -notlike "*mail.onmicrosoft.com" }).Name
}
$CurrentError = $errordescr.exception.message
}
# Creating the session for PS MSOL Service
&$Global:CredentialValidation
} while (($Try -le 2) -and ($null -ne $errordescr))
}
&$Global:DisplayConnect
}
"AzureAD" {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "AzureAD PowerShell"
$CurrentProperty = "Connect Azure"
if ($global:MfaOption -eq 2) {
if (!(Get-Module AzureAD)) {
Import-Module AzureAD -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$token = Get-TokenFromCache("AzureGraph")
if ($null -eq $token) {
$token = Get-Token("AzureGraph")
Connect-AzureAD -AadAccessToken $token.AccessToken -AccountId $global:userPrincipalName -ErrorVariable errordescr -ErrorAction SilentlyContinue | Out-Null
}
else {
try {
$null = Get-AzureADTenantDetail -ErrorAction Stop
}
catch {
Connect-AzureAD -AadAccessToken $token.AccessToken -AccountId $global:userPrincipalName -ErrorVariable errordescr -ErrorAction SilentlyContinue | Out-Null
}
}
}
elseif ($global:MfaOption -eq 1) {
Do {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "AzureAD PowerShell"
$errordescr = $null
$try++
try {
$null = Get-AzureADTenantDetail -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("AzureAD" -in (Get-Module).name)) {
Import-Module AzureAD -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$errordescr = $null
Connect-AzureAd -ErrorVariable errordescr -ErrorAction SilentlyContinue
if ($null -eq $Global:Domain) {
$Global:Domain = (Get-AzureADDomain -ErrorAction SilentlyContinue -ErrorVariable errordescr | Where-Object { $_.name -like "*.onmicrosoft.com" } | Where-Object { $_.name -notlike "*mail.onmicrosoft.com" }).Name
}
$CurrentError = $errordescr.exception.message
}
# Creating the session for PS MSOL Service
&$Global:CredentialValidation
}
while (($Try -le 2) -and ($null -ne $errordescr))
}
&$Global:DisplayConnect
}
"AzureADPreview" {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "AzureADPreview PowerShell"
$CurrentProperty = "Connect AzureADPreview"
# Temporary: Forcing to connect to AzureAD only with promts
# With AADGraph token Get-AzureADAuditSignInLogs fails with: Object reference not set to an instance of an object
# With both AADGraph and MSGraph is failing with:
# User missing required MsGraph permission to access this API, please get any of the following permission for the user: AuditLog.Read.All
#$global:MfaOption
# 1 - Modern with MFA
# 2 - Modern with no MFA (not checking to avoid connection based on AADGraph - checked against 3 should happen)
if ($global:MfaOption -eq 3) {
if (!(Get-Module AzureADPreview)) {
Import-Module AzureADPreview -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$token = Get-TokenFromCache("AzureGraph")
if ($null -eq $token) {
$token = Get-Token("AzureGraph")
AzureADPreview\Connect-AzureAD -AadAccessToken $token.AccessToken -AccountId $global:userPrincipalName -ErrorVariable errordescr -ErrorAction SilentlyContinue | Out-Null
}
else {
try {
$null = AzureADPreview\Get-AzureADTenantDetail -ErrorAction Stop
}
catch {
AzureADPreview\Connect-AzureAD -AadAccessToken $token.AccessToken -AccountId $global:userPrincipalName -ErrorVariable errordescr -ErrorAction SilentlyContinue | Out-Null
}
}
}
elseif (($global:MfaOption -eq 1) -or ($global:MfaOption -eq 2)) {
Do {
$errordescr = $null
$try++
try {
$null = AzureADPreview\Get-AzureADTenantDetail -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("AzureADPreview" -in (Get-Module).name)) {
Import-Module AzureADPreview -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$errordescr = $null
AzureADPreview\Connect-AzureAD -ErrorVariable errordescr -ErrorAction SilentlyContinue
if ($null -eq $Global:Domain) {
$Global:Domain = (AzureADPreview\Get-AzureADDomain -ErrorAction SilentlyContinue -ErrorVariable errordescr | Where-Object { $_.name -like "*.onmicrosoft.com" } | Where-Object { $_.name -notlike "*mail.onmicrosoft.com" }).Name
}
$CurrentError = $errordescr.exception.message
}
# Creating the session for PS MSOL Service
&$Global:CredentialValidation
} while (($Try -le 2) -and ($null -ne $errordescr))
}
&$Global:DisplayConnect
}
# Connect to Exchange Online PowerShell
"EXO" {
# Defining the banner variable and clear the errors
$CurrentProperty = "Connect EXO"
$Global:Error.Clear();
$Global:banner = "Exchange Online PowerShell - Modern"
if ($global:MfaOption -eq 2) {
$token = Get-TokenFromCache("EXO")
if ($null -eq $token) {
$token = Get-Token("EXO")
Get-PSSession -name EXO -ErrorAction SilentlyContinue | Remove-PSSession -Confirm:$false
# Build the auth information
$Authorization = "Bearer {0}" -f $Token.AccessToken
$UserId = ($Token.UserInfo.DisplayableId).tostring()
# create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential($UserId, $Password)
# Create and import the session
$Session = New-PSSession -Name EXO -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true' -Credential $Credtoken -SessionOption $Global:PSsettings -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue'
}
else {
try {
$null = Get-OrganizationConfig -ErrorAction Stop
}
catch {
Get-PSSession -name EXO -ErrorAction SilentlyContinue | Remove-PSSession -Confirm:$false
# Build the auth information
$Authorization = "Bearer {0}" -f $Token.AccessToken
$UserId = ($Token.UserInfo.DisplayableId).tostring()
# create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential($UserId, $Password)
# Create and import the session
$Session = New-PSSession -Name EXO -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true' -Credential $Credtoken -SessionOption $Global:PSsettings -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue'
}
}
}
elseif ($global:MfaOption -eq 1) {
# The loop for re-entering credentials in case they are wrong and for re-connecting
Do {
$try++
try {
$null = Get-OrganizationConfig -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("ExchangeOnlineManagement" -in (Get-Module).Name)) {
Import-Module ExchangeOnlineManagement -Global -DisableNameChecking -Force -ErrorAction SilentlyContinue
}
$errordescr = $null
if (($null -eq $Global:EXOSession ) -or ($Global:EXOSession.State -eq "Closed") -or ($Global:EXOSession.State -eq "Broken")) {
Connect-ExchangeOnline -UserPrincipalName $global:UserPrincipalName -PSSessionOption $PSsettings -ShowBanner:$false -ErrorVariable errordescr -ErrorAction Stop
$Global:EXOSession = Get-PSSession | Where-Object { ($_.name -like "ExchangeOnlineInternalSession*") -and ($_.ConnectionUri -like "*outlook.office365.com*") -and ($_.state -eq "Opened") }
$CurrentError = $errordescr.exception
Import-Module (Import-PSSession $EXOSession -AllowClobber -DisableNameChecking) -Global -DisableNameChecking -ErrorAction SilentlyContinue
$null = Get-OrganizationConfig -ErrorAction SilentlyContinue -ErrorVariable errordescr
$CurrentError = $errordescr.exception.message + $Global:Error[0]
}
}
&$Global:CredentialValidation
} while (($Try -le 2) -and ($Global:Error))
}
&$Global:DisplayConnect
}
# Connecto to EXO Basic Authentication (not recommended unless you want to test secifically BasicAuth)
"ExoBasic" {
If ($null -eq $Global:O365Cred) {
&$Global:UserCredential
}
try {
$Global:EXOSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $global:O365Cred -Authentication "Basic" -AllowRedirection -SessionOption $PSsettings -ErrorVariable errordescr -ErrorAction Stop
$CurrentError = $errordescr.exception
Import-Module (Import-PSSession $EXOSession -AllowClobber -DisableNameChecking) -Global -DisableNameChecking -ErrorAction SilentlyContinue
$CurrentDescription = "Success"
$Global:Domain = Get-AcceptedDomain | Where-Object { $_.name -like "*.onmicrosoft.com" } | Where-Object { $_.name -notlike "*mail.onmicrosoft.com" }
}
catch {
$CurrentDescription = "`"" + $CurrentError.ErrorRecord.Exception + "`""
}
&$Global:DisplayConnect
}
# Connect to EXO2
"EXO2" {
$CurrentProperty = "Connect EXOv2"
Do {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "EXOv2 PowerShell"
$errordescr = $null
$try++
try {
$null = Get-EXOMailbox -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("ExchangeOnlineManagement" -in (Get-Module).name)) {
Import-Module ExchangeOnlineManagement -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$errordescr = $null
Connect-ExchangeOnline -PSSessionOption $PSsettings -ErrorVariable errordescr -ErrorAction SilentlyContinue -ShowBanner:$false
$null = get-EXOMailbox -ErrorVariable errordescr
$CurrentError = $errordescr.exception.message
}
# Creating the session for PS MSOL Service
&$Global:CredentialValidation
}
while (($Try -le 2) -and ($null -ne $errordescr))
&$Global:DisplayConnect
}
# Connect to EOP
"EOP" {
# Defining the banner variable and clear the errors
$CurrentProperty = "Connect EOP"
$Global:Error.Clear();
$Global:banner = "Exchange Online Protection PowerShell - Modern"
if ($global:MfaOption -eq 2) {
$token = Get-TokenFromCache("EXO")
if ($null -eq $token) {
$token = Get-Token("EXO")
Get-PSSession -name EOP -ErrorAction SilentlyContinue | Remove-PSSession -Confirm:$false
# Build the auth information
$Authorization = "Bearer {0}" -f $Token.AccessToken
$UserId = ($Token.UserInfo.DisplayableId).tostring()
# create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential($UserId, $Password)
# Create and import the session
$Session = New-PSSession -Name EOP -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://ps.protection.outlook.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true' -Credential $Credtoken -SessionOption $Global:PSsettings -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue'
}
else {
try {
$null = Get-OrganizationConfig -ErrorAction Stop
}
catch {
Get-PSSession -name EOP -ErrorAction SilentlyContinue | Remove-PSSession -Confirm:$false
# Build the auth information
$Authorization = "Bearer {0}" -f $Token.AccessToken
$UserId = ($Token.UserInfo.DisplayableId).tostring()
# create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential($UserId, $Password)
# Create and import the session
$Session = New-PSSession -Name EOP -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://ps.protection.outlook.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true' -Credential $Credtoken -SessionOption $Global:PSsettings -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue'
}
}
}
elseif ($global:MfaOption -eq 1) {
# The loop for re-entering credentials in case they are wrong and for re-connecting
Do {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "Exchange Online Protection PowerShell"
$try++
# Creating EOP PS session
$Global:EOPSession = New-PSSession -ConfigurationName EOP -ConnectionUri "https://ps.protection.outlook.com/powershell-liveid" -Credential $global:O365Cred -Authentication "Basic" -AllowRedirection -SessionOption $PSsettings -ErrorVariable errordescr -ErrorAction SilentlyContinue
$CurrentError = $errordescr.exception
Import-Module (Import-PSSession $EOPSession -AllowClobber -DisableNameChecking ) -Global -DisableNameChecking -ErrorAction SilentlyContinue
# Connection Errors check (mostly for wrong credentials reasons)
&$Global:CredentialValidation
$Global:Domain = Get-AcceptedDomain | Where-Object { $_.name -like "*.onmicrosoft.com" } | Where-Object { $_.name -notlike "*mail.onmicrosoft.com" }
}
while (($Try -le 2) -and ($Global:Error))
}
&$Global:DisplayConnect
}
# Connect to Compliance Center Online
"SCC" {
# The loop for re-entering credentials in case they are wrong and for re-connecting
# Defining the banner variable and clear the errors
$CurrentProperty = "Connect SCC"
$Global:Error.Clear();
$Global:banner = "Security & Compliance Online PowerShell - Modern"
if ($global:MfaOption -eq 2) {
$token = Get-TokenFromCache("EXO")
if ($null -eq $token) {
$token = Get-Token("EXO")
Get-PSSession -name SCC -ErrorAction SilentlyContinue | Remove-PSSession -Confirm:$false
# Build the auth information
$Authorization = "Bearer {0}" -f $Token.AccessToken
$UserId = ($Token.UserInfo.DisplayableId).tostring()
# create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential($UserId, $Password)
# Create and import the session
$Session = New-PSSession -Name SCC -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://ps.compliance.protection.outlook.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true' -Credential $Credtoken -SessionOption $Global:PSsettings -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue' -Prefix cc
}
else {
try {
$null = Get-OrganizationConfig -ErrorAction Stop
}
catch {
Get-PSSession -name SCC -ErrorAction SilentlyContinue | Remove-PSSession -Confirm:$false
# Build the auth information
$Authorization = "Bearer {0}" -f $Token.AccessToken
$UserId = ($Token.UserInfo.DisplayableId).tostring()
# create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential($UserId, $Password)
# Create and import the session
$Session = New-PSSession -Name SCC -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true' -Credential $Credtoken -SessionOption $Global:PSsettings -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue'
}
}
}
elseif ($global:MfaOption -eq 1) {
Do {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "Security&Compliance Online PowerShell - Modern & MFA"
$try++
try {
$null = Get-ccUser -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("ExchangeOnlineManagement" -in (Get-Module).Name)) {
Import-Module ExchangeOnlineManagement -Global -DisableNameChecking -Force -ErrorAction SilentlyContinue
}
$errordescr = $null
if (($null -eq $Global:IPPSSession ) -or ($Global:IPPSSession.State -eq "Closed") -or ($Global:IPPSSession.State -eq "Broken")) {
Connect-IPPSSession -UserPrincipalName $global:UserPrincipalName -PSSessionOption $PSsettings -ErrorVariable errordescr -ErrorAction Stop -Prefix cc
$Global:IPPSSession = Get-PSSession | Where-Object { ($_.name -like "ExchangeOnlineInternalSession*") -and ($_.ConnectionUri -like "*compliance.protection.outlook.com*") -and ($_.state -eq "Opened") }
$CurrentError = $errordescr.exception
Import-Module (Import-PSSession $IPPSSession -AllowClobber -DisableNameChecking) -Global -DisableNameChecking -ErrorAction SilentlyContinue -Prefix cc
#$null = Get-OrganizationConfig -ErrorAction SilentlyContinue -ErrorVariable errordescr
#$CurrentError = $errordescr.exception.message + $Global:Error[0]
}
}
&$Global:CredentialValidation
} while (($Try -le 2) -and ($Global:Error))
}
&$Global:DisplayConnect
}
#Connect to SharePoint Online PowerShell
"SPO" {
$Global:Error.Clear();
Import-Module MSOnline ;
If ($null -eq $Global:O365Cred) {
&$Global:UserCredential
}
# The loop for re-entering credentials in case they are wrong and for re-connecting
$CurrentProperty = "Connect SPO"
Do {
#### Update_Razvan (conditie pentru admin care nu foloseste onmicrosoft.com si verificare conectare MSOL pentru a lua domeniul)
If ($O365Cred.UserName -like "*.onmicrosoft.com") {
If ($O365Cred.UserName -like "*.mail.onmicrosoft.com") {
$DomainHost = (($O365Cred.UserName -split ".mail.onmicrosoft.com")[0].Substring(0) -split "@")[1].Substring(0)
&$Global:SPOConnectBlock
}
$DomainHost = (($O365Cred.UserName -split ".onmicrosoft.com")[0].Substring(0) -split "@")[1].Substring(0)
&$Global:SPOConnectBlock
}
Else {
If ($null -ne $domain) {
# Substract the domain host name out of the tenant name
$DomainHost = ($domain.name -split ".onmicrosoft.com")
&$Global:SPOConnectBlock
}
Else {
$Global:Error.Clear();
$Global:banner = "SharePoint Online PowerShell"
$try++
$URL = read-host "Please Input the connection URL (i.e.: https://Tenant_Domain-admin.sharepoint.com/)"
Connect-SPOService -Url $URL -credential $O365Cred -ErrorVariable errordescr -ErrorAction SilentlyContinue
&$Global:CredentialValidation
}
}
}
while (($Try -le 2) -and ($null -ne $Global:Error))
&$Global:DisplayConnect
}
# Connect to Skype Online PowerShell
"SFB" {
$Global:Error.Clear();
Import-Module MSOnline ;
If ($null -eq $Global:O365Cred) {
&$Global:UserCredential
}
# The loop for re-entering credentials in case they are wrong and for re-connecting
$CurrentProperty = "Connect SFB"
Do {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "Skype for Business Online PowerShell"
$try++
# Import SFB Online PS module
Import-Module LyncOnlineConnector
# Creating a new SFB Online PS Session
$global:sfboSession = New-CsOnlineSession -Credential $global:O365Cred -ErrorVariable errordescr
$CurrentError = $errordescr.exception
Import-Module (Import-PSSession $sfboSession -DisableNameChecking -AllowClobber) -Global -DisableNameChecking
# Credentials check
&$Global:CredentialValidation
}
while (($Try -le 2) -and ($null -ne $Global:Error))
&$Global:DisplayConnect
}
# Connect to AIPService PowerShell
"AIPService" {
# Defining the banner variable and clear the errors
$Global:Error.Clear();
$Global:banner = "AIP PowerShell"
$CurrentProperty = "Connect AIP"
if ($global:MfaOption -eq 2) {
if (!(Get-Module AIPService)) {
Import-Module AIPService -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$token = Get-TokenFromCache("AIPService")
if ($null -eq $token) {
$token = Get-Token("AIPService")
Connect-AipService -AccessToken $token.AccessToken -ErrorAction SilentlyContinue | Out-Null
}
else {
try {
$null = Get-AipServiceConfiguration -ErrorAction Stop
}
catch {
Connect-AipService -AccessToken $token.AccessToken -ErrorAction SilentlyContinue | Out-Null
}
}
}
elseif ($global:MfaOption -eq 1) {
do {
$Global:Error.Clear();
$Global:banner = "AIPService PowerShell"
$errordescr = $null
$try++
try {
$null = Get-AipServiceConfiguration -ErrorAction Stop
}
catch {
Write-Host "$CurrentProperty"
if (!("AIPService" -in (Get-Module).name)) {
Import-Module AIPService -Global -DisableNameChecking -ErrorAction SilentlyContinue
}
$errordescr = $null
$Global:Error.Clear();
Connect-AipService -ErrorVariable errordescr -ErrorAction SilentlyContinue
$null = Get-AipServiceConfiguration -ErrorVariable errordescr -ErrorAction SilentlyContinue
$CurrentError = $errordescr.exception.message
}
&$Global:CredentialValidation
} while (($Try -le 2) -and ($null -ne $Global:Error))
}
&$Global:DisplayConnect
}
"ADSync" {
try {
Import-Module ADSync -DisableNameChecking -Global -ErrorAction SilentlyContinue
$CurrentDescription = "Success"
}
catch {
$CurrentDescription = "`"" + $CurrentError.ErrorRecord.Exception + "`""
}
}
}
}
#endregion Connection scripts region
Function Set-GlobalVariables {
Clear-Host
Write-Host
$global:FormatEnumerationLimit = -1
$script:PSModule = $ExecutionContext.SessionState.Module
$script:modulePath = $script:PSModule.ModuleBase
$global:ts = Get-Date -Format yyyyMMdd_HHmmss
$global:Path = [Environment]::GetFolderPath("Desktop")
$Global:Path += "\PowerShellOutputs"
$global:WSPath = "$Path\PowerShellOutputs_$ts"
$global:starline = New-Object String '*', 5
$global:addTypeAzureAD = $false
$global:MfaOption = 0;
#$Global:ExtractXML_XML = "Get-MigrationUserStatistics ", "Get-ImapSubscription "
$global:Disclaimer = 'Note: Before you run the script:
The sample scripts are not supported under any Microsoft standard support program or service.
The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims
all implied warranties including, without limitation, any implied warranties of merchantability
or of fitness for a particular purpose. The entire risk arising out of the use or performance of
the sample scripts and documentation remains with you. In no event shall Microsoft, its authors,
or anyone else involved in the creation, production, or delivery of the scripts be liable for any
damages whatsoever (including, without limitation, damages for loss of business profits, business
interruption, loss of business information, or other pecuniary loss) arising out of the use of or
inability to use the sample scripts or documentation, even if Microsoft has been advised of the
possibility of such damages.
'
$global:MfaDisclaimer = @"
1. Please note that not all services allow PowerShell connection with MFA! Example: AIPService module doesn`'t support MFA
2. Using an account with MFA will generate multiple prompts for different Office 365 workloads
3. If you require to have an account with MFA, you can set trusted IPs from which MFA prompt won't be required. See article: https://docs.microsoft.com/azure/active-directory/authentication/howto-mfa-mfasettings#trusted-ips
"@
Write-Host $global:Disclaimer -ForegroundColor Red
Read-Key
if (!(Test-Path $Path)) {
Write-Host "We are creating the following folder $Path"
New-Item -Path $Path -ItemType Directory -Confirm:$False | Out-Null
}
if (!(Test-Path $WSPath)) {
Write-Host "We are creating the following folder $WSPath"
New-Item -Path $WSPath -ItemType Directory -Confirm:$False | Out-Null
}
$global:outputFile = "$WSPath\Log_$ts.csv"
$global:columnLabels = "Time, Function, Step, Description"
Out-File -FilePath $outputFile -InputObject $columnLabels -Encoding UTF8 | Out-Null
Set-Location $WSPath
Write-Host "`n"
#if ($null -eq $global:credential)
#{
#$global:userPrincipalName = Get-ValidEmailAddress("UserPrincipalName used to connect to Office 365 Services")
#Write-Host "Please note that depening the Office 365 Services we need to connect, you might be asked to re-add the UserPrincipalName in another Authentication Form!" -ForegroundColor Yellow
#Start-Sleep -Seconds 5
#}
}
function Get-ValidEmailAddress([string]$EmailAddressType) {
[int]$count = 0
do {
Write-Host "Enter Valid $EmailAddressType`: " -ForegroundColor Cyan -NoNewline
[string]$EmailAddress = Read-Host
[bool]$valid = ($EmailAddress.Trim() -match "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$")
if (!$valid) {
$InvalidEmailAddressWarning = "Inputed Email Address `"$EmailAddress`" does not pass O365Troubleshooters format validation"
Write-Warning -Message $InvalidEmailAddressWarning
Write-Log -function "Get-ValidEmailAddress" -step "input address" -Description $InvalidEmailAddressWarning
}
$count++
}
while (!$valid -and ($count -le 2))
if ($valid) {
return $EmailAddress.Trim()
}
else {
[string]$Description = "Received 3 invalid email address inputs, the script will return to O365Troubleshooters Main Menu"
Write-Host "`n$Description" -ForegroundColor Red
Start-Sleep -Seconds 3
Write-Log -function "Get-ValidEmailAddress" -step "input address" -Description $Description
Read-Key
Start-O365TroubleshootersMenu
}
<# Old recurse of the function - replaced by new version with counter.
if($EmailAddress -match "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$")
{
}
else
{
Get-ValidEmailAddress($EmailAddressType)
}
#>
}
function Read-IntFromConsole {
param ([string][Parameter(Mandatory = $true)]$IntType)
[int]$count = 0
do {
[bool]$valid = $true
Write-Host "Enter Valid $IntType`: " -ForegroundColor Cyan -NoNewline
try {
[int]$IntFromConsole = Read-Host
if ($IntFromConsole -eq 0) {