-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSPF-AD-Sync.ps1
1931 lines (1776 loc) · 65.3 KB
/
SPF-AD-Sync.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
#*===============================================================================
# Filename : SPFoundation-AD-Sync.ps1
# Version : 1.4.2
#*===============================================================================
# Author : Florent CHAUVIN
# Company: LINKBYNET
#*===============================================================================
# Created: FCH - 12 december 2014
# Modified: FCH - 8 september 2015
#*===============================================================================
# Description :
# Script to synchronize SharePoint Foundation user profile with their domain's account
# Advanced synchronization need 'Active Directory module for Windows PowerShell' feature
# available with Windows 2008 R2 or higher.
#*===============================================================================
#*===============================================================================
# Variables Configuration
#*===============================================================================
#Path for script logging
$Global:Log = ".\" + (get-date -uformat '%Y%m%d-%H%M') + "-SPFoundation_AD_Sync.log"
#List of forest which users belong.Leave the value "" to test domain without adding the name of forest to the netbios domain name. Example: $Global:ForestList = @("","dnsforestname")
$Global:ForestList = @("")
#If needed, username and password for forest access (Must be created on one domain of all forest to access)
$Global:ForestAccessUsername = ""
$Global:ForestAccessPassword = ""
#Debug mode, use to understand why account don't synchronize properly.
$Global:DebugMode = $False
#Delete account with domain unreachable or not found in domain (Advanced synchronization). The deletion is performed only if the number of account to delete is less than 30% of the number of synchronized account
$Global:DeleteUSersNotFound = $True
#Enable sending EMail
$Global:SendMail = $False
#Multiple recipients must be comma separated
$Global:emailFrom = gwmi Win32_ComputerSystem| %{$_.DNSHostName + '@' + $_.Domain}
$Global:emailTo = ""
$Global:emailCC =""
$Global:emailOnErrorTO = ""
$Global:emailOnErrorCC = ""
$Global:smtpServer = ""
#*===============================================================================
# Functions
#*===============================================================================
# Region : Create Folder if doesn't exist
function Test-FilePath-Create
{
param([String]$FullFilename)
If ($FullFilename -ne $null)
{
If (($FullFilename.substring(($FullFilename.length)-1,1)) -eq "`"")
{
$PathFilename = ($FullFilename.substring(0,$FullFilename.LastIndexOf("\")) + "`"")
}
Else
{
$PathFilename = ($FullFilename.substring(0,$FullFilename.LastIndexOf("\")))
}
If (!(Test-Path -literalPath ($PathFilename)))
{
New-Item $PathFilename -type directory -errorAction SilentlyContinue | out-null
If (Test-Path -literalPath ($PathFilename)){Write-Host "|-> Creation of folder " $PathFilename -Fore Green}
Else {Write-Host "|-> Failed to create folder " $PathFilename -Fore Red}
}
}
}
#EndRegion
#Region : Load the SharePoint snap-in for PowerShell
function Load-Snapin
{
<#
To avoid introducing memory-leaks in your PowerShell sessions that you spawn up without using the Sharepoint Management Shell, remembe to either call SharePoint.ps1 or at least set $Host.Runspace.ThreadOptions = "ReuseThread" before executing any code.
http://andersrask.sharepointspace.com/Lists/Posts/Post.aspx?ID=4
#>
$ver = $host | select version
if ($ver.Version.Major -gt 1)
{
$Host.Runspace.ThreadOptions = "ReuseThread"
}
$snapin = (Get-PSSnapin -name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue)
if ($snapin -ne $null) {
Write-Host "|--> SharePoint Snap-in is loaded" -fore Green
}
else
{
try
{
Write-host "|--> SharePoint Snap-in not found. Action: Loading SharePoint Snap-in."
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
}
catch
{
$errText = $error[0].Exception.Message
Write-Host "|--> Loading of SharePoint Snap-in failed.Reason: $errText" -fore Red
Exit
}
}
}
#EndRegion
#LoadActiveDirectoryModule : Load Active Directory module
function LoadActiveDirectoryModule
{
If((($([System.Environment]::OSVersion.Version).Major -eq 6) -and ($([System.Environment]::OSVersion.Version).Minor -ge 1)) -or (([System.Environment]::OSVersion.Version).Major -gt 6))
{
Import-Module ServerManager
$RSATADPowershell = Get-WindowsFeature | ?{$_.name -eq "RSAT-AD-Powershell"}
If ($RSATADPowershell -ne $null)
{
if($RSATADPowershell.Installed -eq $True)
{
try
{
Import-Module ActiveDirectory
Write-Host "|--> ActiveDirectory Module has been imported." -fore Green
$Global:ImportModuleAD = $True
}
catch
{
$errText = $error[0].Exception.Message
Write-Host "|--> Import of Active Directory module failed.Reason: $errText" -fore Red
$Global:ImportModuleAD = $False
}
}
Else
{
Write-Host "|--> Cannot load Active directory module because 'Active Directory module for Windows PowerShell' feature is not installed. Extended attributes won't be synchronized." -fore Red
$Global:ImportModuleAD = $False
}
}
Else
{
Write-Host "|--> Cannot load Active directory module because 'Active Directory module for Windows PowerShell' feature is not available on this operating system. Extended attributes won't be synchronized." -fore Red
$Global:ImportModuleAD = $False
}
}
Else
{
Write-Host "|--> Cannot load Active directory module because 'Active Directory module for Windows PowerShell' feature is not available on this operating system. Extended attributes won't be synchronized." -fore Red
$Global:ImportModuleAD = $False
}
}
#EndRegion
#Region Determine whether SharePoint edition is SharePoint Foundation
function Is-Foundation
{
# Note: Standard & Enterprise installations return the Foundation SKU as well as the Enterprise SKU or Standard SKU.
$2010enterpriseSKU = "D5595F62-449B-4061-B0B2-0CBAD410BB51"
$2010standardSKU = "3FDFBCC8-B3E4-4482-91FA-122C6432805C"
$2013enterpriseSKU = "B7D84C2B-0754-49E4-B7BE-7EE321DCE0A9"
$2013standardSKU = "C5D855EE-F32B-4A1C-97A8-F0A28CE02F9C"
try
{
$products = Get-SPFarm | Select Products -ErrorAction Stop
foreach ($product in $products)
{
$product = $product.Products
if (($product -contains $2010enterpriseSKU) -or ($product -contains $2010standardSKU) -or ($product -contains $2013enterpriseSKU) -or ($product -contains $2013standardSKU))
{
return $false
}
return $true
}
}
catch
{
$errText = $error[0].Exception.Message
Write-Host "|--> Unable to determine version of SharePoint.Reason: $errText"
}
}
#EndRegion
#Region Test if user's domain is reachable, one time by domain for all users to synchronize
Function TestDomainAvailability
{
Param
(
$_DomainName
)
Write-host " |--> Testing the availability of the domain '$_DomainName'"
If(($DomainReachable | Where-Object {$_.Name -eq $_DomainName}) -ne $null)
{
$DomainTested = $DomainReachable | Where-Object {$_.Name -eq $_DomainName}
$Global:DomainTestedWithSuccess = $True
$Global:DomainName = $DomainTested.CompleteName
$Global:DomainCred = $DomainTested.Credential
Write-host " |--> The domain controller for domain '$_DomainName' has been be listed in the previous test" -fore Green
}
ElseIf(($DomainUnReachable | Where-Object {$_.Name -eq $_DomainName}) -ne $null)
{
Write-host " |--> The domain controller for domain '$_DomainName' hasn't been be listed in the previous test.User synchronization can not be performed." -fore Red
$Global:DomainTestedWithSuccess = $False
$Global:CounterUsersDomainUnreachable++
$Global:UsersWithDomainUnreachable += [String]$SPuser.LoginName
}
Else
{
If(!$ForestList)
{
$ForestList = @("")
}
Else
{
If(($ForestList | Where-Object {$_ -eq ""}) -eq $null)
{
$ForestList += ""
}
$ForestList = $ForestList | sort
}
Foreach ($Forest in $ForestList)
{
If($Forest -eq "")
{
[String]$_CompleteDomainName = $_DomainName
}
Else
{
[String]$_CompleteDomainName = $_DomainName + "." + $Forest
Write-host " |--> Testing the availability of the domain '$_DomainName' by adding the name of the Forest '$Forest'"
}
$DomainTested = New-Object -TypeName PSObject
$DomainTested | Add-Member -Type NoteProperty -Name Name -Value $_DomainName
$DomainTested | Add-Member -Type NoteProperty -Name CompleteName -Value $_CompleteDomainName
$DomainTested | Add-Member -Type NoteProperty -Name Credential -Value $False
If($ImportModuleAD -eq $false)
{
Write-host " |--> Test by listing the domain controller with nltest"
# Try to list domain controller of this domain with nltest.exe
$Nltestexe = "nltest.exe"
$NltestParam = "/dcList:" + $_CompleteDomainName
$NlTestResult = [String](& $nltestexe $NltestParam 2>&1)
if($NLTestResult -match ".*ERROR.*|.*UNAVAILABLE.*")
{
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'. Reason: $NlTestResult" -fore Yellow
$Global:DomainUnReachable += $DomainTested
$Global:DomainTestedWithSuccess = $False
}
ElseIf([string]::IsNullOrEmpty($NLTestResult))
{
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'. Reason: Command nltest.exe send empty result, relaunch the script in new Powershell session" -fore Yellow
$Global:DomainTestedWithSuccess = $False
}
Else
{
Write-host " |--> The domain controller for domain '$_CompleteDomainName' are available " -fore Green
$Global:DomainReachable += $DomainTested
$Global:DomainTestedWithSuccess = $True
break
}
}
Else
{
Write-host " |--> Test with 'Get-ADdomain' cmdlet"
$RetryWithCred = $False
Try
{
$GetADDomainTest = Get-ADdomain -server $_CompleteDomainName
If(([string]::IsNullOrEmpty($GetADDomainTest)))
{
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'." -fore Yellow
$Global:DomainUnReachable += $DomainTested
$Global:DomainTestedWithSuccess = $False
}
Else
{
$Global:DomainTestedWithSuccess = $True
$DomainTested.Credential = $False
}
break
}
Catch
{
If (($error[0].Exception.Message -eq "The server has rejected the client credentials.") -or ($error[0].Exception.Message -eq "Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running."))
{
$RetryWithCred = $True
$ErrText = $error[0].Exception.Message
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'. Reason:$ErrText" -fore Yellow
}
Else
{
$ErrText = $error[0].Exception.Message
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'. Reason:$ErrText" -fore Yellow
$Global:DomainUnReachable += $DomainTested
$Global:DomainTestedWithSuccess = $False
}
}
If(($RetryWithCred -eq $True) -and ($ForestAccessUsername -ne ""))
{
Write-host " |--> Testing the availability of the domain '$_CompleteDomainName' by adding credential"
$SecStr = New-Object -TypeName System.Security.SecureString
$ForestAccessPassword.ToCharArray() | ForEach-Object {$SecStr.AppendChar($_)}
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $ForestAccessUsername, $SecStr
Try
{
$GetADDomainTest = Get-ADdomain -server $_CompleteDomainName -Credential $Cred
If(([string]::IsNullOrEmpty($GetADDomainTest)))
{
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'." -fore Yellow
$Global:DomainUnReachable += $DomainTested
$Global:DomainTestedWithSuccess = $False
}
Else
{
$Global:DomainTestedWithSuccess = $True
$DomainTested.Credential = $True
}
break
}
Catch
{
$ErrText = $error[0].Exception.Message
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'. Reason:$ErrText" -fore Yellow
$Global:DomainUnReachable += $DomainTested
$Global:DomainTestedWithSuccess = $False
}
}
}
Remove-variable DomainTested -ErrorAction SilentlyContinue
Remove-variable GetADDomainTest -ErrorAction SilentlyContinue
Remove-variable RetryWithCred -ErrorAction SilentlyContinue
Remove-variable _CompleteDomainName -ErrorAction SilentlyContinue
}
If($DomainTestedWithSuccess -eq $True)
{
Write-host " |--> The domain controller for domain '$_CompleteDomainName' are available " -fore Green
$Global:DomainReachable += $DomainTested
$Global:DomainName = $DomainTested.CompleteName
$Global:DomainCred = $DomainTested.Credential
}
Else
{
Write-Host " |--> Cannot list domain controller for domain '$_CompleteDomainName'. User synchronization can not be performed." -fore Red
$Global:CounterUsersDomainUnreachable++
$Global:UsersWithDomainUnreachable += [String]$SPuser.LoginName
}
Remove-variable DomainTested -ErrorAction SilentlyContinue
Remove-variable GetADDomainTest -ErrorAction SilentlyContinue
Remove-variable RetryWithCred -ErrorAction SilentlyContinue
Remove-variable DomainTestedWithSuccess -ErrorAction SilentlyContinue
Remove-variable _CompleteDomainName -ErrorAction SilentlyContinue
}
}
#EndRegion
#Region Retrieve the user and his properties (Domain Name, SAM Account Name, SID) based on the authentication type of web application
Function Retrieve-User-And-Properties
{
Param
(
$_User,
$LoginName
)
Try
{
If ($DebugMode -eq $True)
{
Write-host "# Debug => Function Retrieve-User-And-Properties" -fore Yellow
}
If($LoginName -eq $true)
{
if ($site.WebApplication.UseClaimsAuthentication)
{
$claim = New-SPClaimsPrincipal $_User -IdentityType WindowsSamAccountName
$Global:SPuser = $web | Get-SPUser -Identity $claim -ErrorAction Stop
}
else
{
$Global:SPuser = $web | Get-SPUser -Identity $_User -ErrorAction Stop
}
}
Else
{
# if ($site.WebApplication.UseClaimsAuthentication)
# {
# $claim = New-SPClaimsPrincipal $_User.LoginName -IdentityType WindowsSamAccountName
# $Global:SPuser = $web | Get-SPUser -Identity $claim -ErrorAction Stop
# }
# else
# {
$Global:SPuser = $web | Get-SPUser -Identity $_User.LoginName -ErrorAction Stop
# }
}
If($claim)
{
[String]$SPUserStr = $Claim.value
If ($DebugMode -eq $True)
{
Write-Host "# Claim.value: "$Claim.value
Write-Host "# SPUserStr: "$SPUserStr
}
}
Else
{
[String]$Global:SPUserStr = $SPUser
If ($DebugMode -eq $True)
{
Write-Host "# SPuser: "$SPuser
Write-Host "# SPUserStr: "$SPUserStr
}
}
#Parse account name to get user name and domain
$SplitSPuser = $SPUserStr.split("\")
$Global:SPUserSAMAccountName = $SplitSPuser[1]
$Global:DomainName = $SplitSPuser[0]
If ($DebugMode -eq $True)
{
Write-Host "# SplitSPuser: "$SplitSPuser
Write-Host "# SPUserSAMAccountName: "$SPUserSAMAccountName
Write-Host "# DomainName: "$DomainName
}
If($DomainName -match "\|")
{
$SplitDomainName = $DomainName.split("|")
$Global:DomainName = $SplitDomainName[1]
If ($DebugMode -eq $True)
{
Write-Host "# SplitDomainName: "$SplitDomainName
Write-Host "# DomainName: "$DomainName
}
}
#Get account ID and SID
$Global:SPUserID = $SPUser.ID
If ($DebugMode -eq $True)
{
Write-Host "# SPUserID: "$SPUserID
}
If($Version -lt 15)
{
$Global:SPUserSID = $SPUser.SID
}
Else
{
$Global:SPUserSID = $SPUser.SystemUserKey
If($SPUserSID -match "\|")
{
$SplitSPUserSID = $SPUserSID.split("|")
$Global:SPUserSID = $SplitSPUserSID[1]
}
}
If ($DebugMode -eq $True)
{
Write-Host "# SPUserSID: "$SPUserSID
}
}
Catch
{
$Global:SPuser = $null
$errText = $error[0].Exception.Message
Write-Host " |--> Failed to retrieve SharePoint User and his properties.Reason: $errText" -fore Red
}
}
#EndRegion
#Region Get AD account and launch check for modification and update
Function GetAndCheckADAccountModification
{
Param
(
$_SPUserSAMAccountName,
$_SPUserSID,
$_SPuser,
$_SPUserStr,
$_DomainName,
$_Cred
)
Try
{
Write-Host " |--> Get user information from domain"
If ($DebugMode -eq $True)
{
Write-host "# Debug => Function GetAndCheckADAccountModification" -fore Yellow
Write-host "# _SPUserSAMAccountName: "$_SPUserSAMAccountName
Write-host "# _SPUserSID: "$_SPUserSID
Write-host "# _SPuser: "$_SPuser
Write-host "# _SPUserStr: "$_SPUserStr
Write-host "# _DomainName: "$_DomainName
Write-host "# _Cred: "$_Cred
}
#Two requests, one by SID and one by SAM Account Name to verify if account have been deleted, recreated (New SID) or modified (New SAM Account Name).
If($_Cred)
{
$SecStr = New-Object -TypeName System.Security.SecureString
$ForestAccessPassword.ToCharArray() | ForEach-Object {$SecStr.AppendChar($_)}
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $ForestAccessUsername, $SecStr
$filter = "SAMAccountName -eq '$($_SPUserSAMAccountName)'"
If ($DebugMode -eq $True)
{
Write-host "# get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone -Credential $Cred"
}
$ADUserBySAMAccountName = get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone -Credential $Cred
If ($_SPUserSID -ne "")
{
$filter = "SID -eq '$($_SPUserSID)'"
If ($DebugMode -eq $True)
{
Write-host "# get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone -Credential $Cred"
}
$ADUserBySID = get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone -Credential $Cred
}
Else
{
$ADUserBySID = $null
}
}
Else
{
$filter = "SAMAccountName -eq '$($_SPUserSAMAccountName)'"
If ($DebugMode -eq $True)
{
Write-host "# get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone"
}
$ADUserBySAMAccountName = get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone
If ($_SPUserSID -ne "")
{
$filter = "SID -eq '$($_SPUserSID)'"
If ($DebugMode -eq $True)
{
Write-host "# get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone"
}
$ADUserBySID = get-aduser -f $filter -server $_DomainName -properties DisplayName, EmailAddress, Department, Title, SAMAccountName, OfficePhone, MobilePhone
}
Else
{
$ADUserBySID = $null
}
}
If ($DebugMode -eq $True)
{
Write-Host "# AD User By SAMAccountName (user properties) :" ($ADUserBySAMAccountName | select *)
Write-Host "# AD User By SID (user properties) :" ($ADUserBySID | select *)
}
If(($ADUserBySAMAccountName -eq $null) -and ($ADUserBySID -eq $null))
{
Write-Host " |--> User $SPUserSAMAccountName not found in domain $DomainName" -fore Red
$Global:ExecuteSynchronize = $False
$Global:CounterUsersAdvancedNotFound++
$Global:UsersNotFound += [String]$SPuser.LoginName
}
Else
{
CheckADAccountModificationAndUpdate -_ADUserBySAMAccountName $ADUserBySAMAccountName -_ADUserBySID $ADUserBySID -_SPuser $_SPuser -_SPUserStr $_SPUserStr -_SPUserSID $_SPUserSID -_DomainName $_DomainName
}
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> Cannot get user information from domain.Reason: $errText " -fore Red
$Global:CounterUsersNativeSynchronizationFailed++
$Global:UsersWithNativeSynchonizationError += [String]$SPuser.LoginName
$Global:CounterUsersAdvancedSynchronizationFailed++
$Global:UsersWithAdvancedSynchonizationError += [String]$SPuser.LoginName
}
Finally
{
Remove-variable ADUserBySAMAccountName -ErrorAction SilentlyContinue
Remove-variable ADUserBySID -ErrorAction SilentlyContinue
}
}
#EndRegion
#Region Check AD account modification and launch update
Function CheckADAccountModificationAndUpdate
{
Param
(
$_ADUserBySAMAccountName,
$_ADUserBySID,
$_SPuser,
$_SPUserStr,
$_SPUserSID,
$_DomainName
)
Try
{
If(($_ADUserBySAMAccountName -ne $null) -and ($_ADUserBySID -eq $null))
{
$ADUserBySAMAccountNameSID = $_ADUserBySAMAccountName.SID
Write-Host " |--> Found $SPUserSAMAccountName account with different SID ($_SPUserSID <> $ADUserBySAMAccountNameSID)" -fore Red
Write-Host " |--> Update SharePoint User with new SID"
$OldSPuser = $_SPuser
UpdateUser -_Identity $_SPuser -_NewAlias $_SPUserStr
Retrieve-User-And-Properties $_SPuser
If ($ADUserBySAMAccountNameSID -eq $SPUserSID)
{
Write-Host " |--> SharePoint user have been successfully updated." -fore Green
$Global:ExecuteSynchronize = $True
$Global:CounterUsersADAccountUpdateSuccess++
$Global:ADUser = $_ADUserBySAMAccountName
}
Else
{
Write-Host " |--> Failed to update SharePoint user. Synchronization of user have been aborted." -fore Red
$Global:ExecuteSynchronize = $False
$Global:CounterUsersADAccountUpdateFailed++
$Global:UsersWithADAccountUpdateError += [String]$OldSPuser.LoginName
}
Remove-variable OldSPuser -ErrorAction SilentlyContinue
Remove-variable ADUserBySAMAccountNameSID -ErrorAction SilentlyContinue
}
ElseIf(($_ADUserBySAMAccountName -eq $null) -and ($_ADUserBySID -ne $null))
{
$ADUserBySIDSAMAccountName = $_ADUserBySID.SAMAccountName
Write-Host " |--> Found $SPUserSAMAccountName account with different SAM Account Name ($SPUserSAMAccountName <> $ADUserBySIDSAMAccountName)"
Write-Host " |--> Update SharePoint User with new SAM Account Name"
$UserNewLoginName = $_DomainName + "\" + $ADUserBySIDSAMAccountName
$OldSPuser = $_SPuser
UpdateUser -_Identity $_SPuser -_NewAlias $UserNewLoginName
Retrieve-User-And-Properties -_User $UserNewLoginName -LoginName $True
If($SPuser -ne $null)
{
Write-Host " |--> SharePoint user have been successfully updated." -fore Green
$Global:ExecuteSynchronize = $True
$Global:CounterUsersADAccountUpdateSuccess++
$Global:ADUser = $_ADUserBySAMAccountName
}
Else
{
Write-Host " |--> Failed to update SharePoint user. Synchronization of user have been aborted." -fore Red
$Global:ExecuteSynchronize = $False
$Global:CounterUsersADAccountUpdateFailed++
$Global:UsersWithADAccountUpdateError += [String]$OldSPuser.LoginName
}
Remove-variable OldSPuser -ErrorAction SilentlyContinue
Remove-variable ADUserBySAMAccountNameSID -ErrorAction SilentlyContinue
Remove-variable ADUserBySIDSAMAccountName -ErrorAction SilentlyContinue
Remove-variable UserNewLoginName -ErrorAction SilentlyContinue
}
Else
{
$ADUserBySIDSID = $_ADUserBySID.SID
$ADUserBySAMAccountNameSID = $_ADUserBySAMAccountName.SID
If($ADUserBySIDSID -eq $ADUserBySAMAccountNameSID)
{
Write-Host " |--> $SPUserSAMAccountName account have been found" -fore Green
$Global:ADUser = $_ADUserBySID
$Global:ExecuteSynchronize = $True
$Global:CounterUsersADAccountUpdateNoModification++
}
Else
{
$ADUserBySIDSAMAccountName = $_ADUserBySID.SAMAccountName
$ADUserBySAMAccountNameSAMAccountName = $_ADUserBySAMAccountName.SAMAccountName
Write-Host " |--> Two account have been found with different SID" -fore Red
Write-Host " |--> Account found by SID : $ADUserBySIDSID / $ADUserBySIDSAMAccountName" -fore Red
Write-Host " |--> Account found by SAM Account Name : $ADUserBySAMAccountNameSID / $ADUserBySAMAccountNameSAMAccountName" -fore Red
Write-Host " |--> Synchronization of user have been aborted." -fore Red
$Global:ExecuteSynchronize = $False
$Global:CounterUsersADAccountUpdateFailed++
$Global:UsersWithADAccountUpdateError += [String]$_SPuser.LoginName
Remove-variable ADUserBySIDSAMAccountName -ErrorAction SilentlyContinue
Remove-variable ADUserBySAMAccountNameSAMAccountName -ErrorAction SilentlyContinue
}
Remove-variable ADUserBySIDSID -ErrorAction SilentlyContinue
Remove-variable ADUserBySAMAccountNameSID -ErrorAction SilentlyContinue
}
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> Failed to check AD account modification.Reason: $errText" -fore Red
}
}
#EndRegion
#Region Update SharePoint User
Function UpdateUser
{
Param
(
$_Identity,
$_NewAlias
)
Try
{
Move-SPUser -Identity $_Identity -newalias $_NewAlias -IgnoreSID -Confirm:$false -ErrorAction Stop
if (!$?)
{
throw $error[0].Exception
}
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> Failed to update SharePoint User.Reason: $errText" -fore Red
}
}
#EndRegion
#Region Control if user attributes have been modified"
Function NativeSynchronization
{
Param
(
$_Identity,
$_Web
)
Try
{
Write-Host " |--> Get current user attributes"
GetCurrentUserAttributes -_Identity $_Identity -_web $_Web
Write-Host " |--> Synchronize with Set-SPuser and SyncFromAD parameter"
Set-SPUser -Identity $_Identity -web $_Web -SyncFromAD -ErrorAction Stop
if (!$?)
{
throw $error[0].Exception
}
Write-Host " |--> Control if user attributes have been modified"
ControlUserAttributesModification -_Identity $_Identity -_web $_Web
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> User synchronization has failed.Reason: $errText" -fore Red
$Global:CounterUsersNativeSynchronizationFailed++
$Global:UsersWithNativeSynchonizationError += [String]$_Identity.LoginName
}
Finally
{
Remove-variable NewUserInfo -ErrorAction SilentlyContinue
Remove-variable NewUserLogin -ErrorAction SilentlyContinue
Remove-variable NewUserdisplayName -ErrorAction SilentlyContinue
Remove-variable NewUserName -ErrorAction SilentlyContinue
Remove-variable NewUserEmail -ErrorAction SilentlyContinue
Remove-variable NewUserLoginName -ErrorAction SilentlyContinue
Remove-variable OldUserInfo -ErrorAction SilentlyContinue
Remove-variable OldUserLogin -ErrorAction SilentlyContinue
Remove-variable OldUserdisplayName -ErrorAction SilentlyContinue
Remove-variable OldUserName -ErrorAction SilentlyContinue
Remove-variable OldUserEmail -ErrorAction SilentlyContinue
Remove-variable OldUserLoginName -ErrorAction SilentlyContinue
}
}
#EndRegion
#Region Get current user attributes
Function GetcurrentUserAttributes
{
Param
(
$_Identity,
$_Web
)
Try
{
$Global:OldUserInfo = Get-SPUser -Identity $_Identity -web $_Web
$Global:OldUserLogin = $OldUserInfo.UserLogin
$Global:OldUserdisplayName = $OldUserInfo.DisplayName
$Global:OldUserName = $OldUserInfo.Name
$Global:OldUserEmail = $OldUserInfo.Email
$Global:OldUserLoginName = $OldUserInfo.LoginName
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> Failed to get current user attributes.Reason: $errText" -fore Red
}
}
#EndRegion
#Region Control if user attributes have been modified"
Function ControlUserAttributesModification
{
Param
(
$_Identity,
$_Web
)
Try
{
$Global:NewUserInfo = Get-SPUser -Identity $_Identity -web $_Web
$Global:NewUserLogin = $NewUserInfo.UserLogin
$Global:NewUserdisplayName = $NewUserInfo.DisplayName
$Global:NewUserName = $NewUserInfo.Name
$Global:NewUserEmail = $NewUserInfo.Email
$Global:NewUserLoginName = $NewUserInfo.LoginName
$Global:UserModified = $False
If ($DebugMode -eq $True)
{
Write-host "# Debug => Function ControlUserAttributesModification" -fore Yellow
Write-host "# SPuser all properties:"
$NewUserInfo | select *
Write-host "# OldValue"
Write-host "# OldUserLogin:" $OldUserLogin
Write-host "# OldUserdisplayName:"$OldUserdisplayName
Write-host "# OldUserName:"$OldUserName
Write-host "# OldUserEmail:"$OldUserEmail
Write-host "# OldUserLoginName:"$OldUserLoginName
Write-host "# NewValue"
Write-host "# NewUserLogin:"$NewUserLogin
Write-host "# NewUserdisplayName:"$NewUserdisplayName
Write-host "# NewUserName:"$NewUserName
Write-host "# NewUserEmail:"$NewUserEmail
Write-host "# NewUserLoginName:"$NewUserLoginName
}
If ($OldUserLogin -ne $NewUserLogin)
{
Write-Host " |--> User Login has been modified ($OldUserLogin ==> $NewUserLogin)" -fore Green
$UserModified = $True
}
If ($OldUserdisplayName -ne $NewUserdisplayName)
{
Write-Host " |--> User Display Name has been modified ($OldUserdisplayName ==> $NewUserdisplayName)" -fore Green
$UserModified = $True
}
If ($OldUserName -ne $NewUserName)
{
Write-Host " |--> User Name has been modified ($OldUserName ==> $NewUserName)" -fore Green
$UserModified = $True
}
If ($OldUserEmail -ne $NewUserEmail)
{
Write-Host " |--> User Email has been modified ($OldUserEmail ==> $NewUserEmail)" -fore Green
$UserModified = $True
}
If ($OldUserLoginName -ne $NewUserLoginName)
{
Write-Host " |--> User Login Name has been modified ($OldUserLoginName ==> $NewUserLoginName)" -fore Green
$UserModified = $True
}
If ($UserModified -eq $False)
{
Write-Host " |--> User hasn't been modified" -fore Green
$Global:CounterUsersNativeSynchronizationNoModification++
}
Else
{
$Global:CounterUsersNativeSynchronizationSuccess++
}
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> Failed to control current user attributes modification.Reason: $errText" -fore Red
}
}
#EndRegion
#Region Get user extended information from SharePoint
Function GetUserExtendedInformation
{
Param
(
$_SPUserID,
$_Web
)
Try
{
If ($DebugMode -eq $True)
{
Write-host "# Debug => Function GetUserExtendedInformation" -fore Yellow
Write-Host "# _SPUserID:"$_SPUserID
Write-Host "# _Web:"$_Web
}
$Global:list = $_Web.Lists["User Information List"]
$Global:Item = $list.GetItemById($_SPUserID)
}
Catch
{
$errText = $error[0].Exception.Message
$Global:List = $Null
$Global:Item = $Null
Write-Host " |--> Failed to get user extended information from SharePoint.Reason: $errText" -fore Red
}
}
#EndRegion
#Region Check user extended information from SharePoint
Function CheckUserExtendedInformation
{
Param
(
$_list,
$_item
)
$_item | Foreach {
Try
{
$Global:OldUserJobTitle = $_item["JobTitle"]
$Global:OldUserDepartment = $_item["Department"]
If(!($IsFoundation))
{
$Global:OldUserWorkPhone = $_item["WorkPhone"]
}
$Global:OldUserMobilePhone = $_item["MobilePhone"]
$Global:OldUserTitle = $_item["Title"]
}
Catch
{
$errText = $error[0].Exception.Message
Write-Host " |--> Failed to check user extended information from SharePoint.Reason: $errText" -fore Red
}
}
}
#EndRegion
#Region Update user extended information from SharePoint
Function UpdateUserExtendedInformation
{
Param
(
$_list,
$_item,
$_ADUser
)
$_item | Foreach {
Try
{
If ($DebugMode -eq $True)
{
Write-host "# Debug => Function UpdateUserExtendedInformation" -fore Yellow
Write-Host "# SP User Jobtitle :"$_item["JobTitle"]
[string]::IsNullOrEmpty($_item["JobTitle"])
Write-Host "# AD User Title :"$_ADUser.title
[string]::IsNullOrEmpty($_ADUser.title)
}
If((![string]::IsNullOrEmpty($_ADUser.title)) -and ($_item["JobTitle"] -ne [string]$_ADUser.title))
{
Write-Host " |--> Job Title must be updated"
$_item["JobTitle"] = [string]$_ADUser.title
}
If ($DebugMode -eq $True)
{
Write-Host "# SP User Department :"$_item["Department"]
Write-Host "# AD User Department :"$_ADUser.department
}
If((![string]::IsNullOrEmpty($_ADUser.department)) -and ($_item["Department"] -ne [string]$_ADUser.department))
{
Write-Host " |--> Department must be updated"
$_item["Department"] = [string]$_ADUser.department
}
If(!($IsFoundation))
{
If ($DebugMode -eq $True)
{
Write-Host "# SP User WorkPhone:"$_item["WorkPhone"]
Write-Host "# AD User OfficePhone :"$_ADUser.OfficePhone
}
If((![string]::IsNullOrEmpty($_ADUser.OfficePhone)) -and ($item["WorkPhone"] -ne [string]$_ADUser.OfficePhone))
{
Write-Host " |--> Office Phone must be updated"
$_item["WorkPhone"] = [string]$_ADUser.OfficePhone