-
Notifications
You must be signed in to change notification settings - Fork 214
/
AzureADConnectAPI.ps1
2434 lines (2032 loc) · 92.7 KB
/
AzureADConnectAPI.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
## Directory Sync API functions
# NOTE: Azure AD Sync API gets redirected quite often 2-3 times per request.
# Therefore the functions need to be called recursively and use $Recursion parameter.
# Get synchronization configuration using Provisioning and Azure AD Sync API
# May 6th 2020
function Get-SyncConfiguration
{
<#
.SYNOPSIS
Gets tenant's synchronization configuration
.DESCRIPTION
Gets tenant's synchronization configuration using Provisioning and Azure AD Sync API.
If the user doesn't have admin rights, only a subset of information is returned.
.Parameter AccessToken
Access Token
.Example
Get-AADIntSyncConfiguration
AllowedFeatures : {ObjectWriteback, , PasswordWriteback}
AnchorAttribute : mS-DS-ConsistencyGuid
ApplicationVersion : 1651564e-7ce4-4d99-88be-0a65050d8dc3
ClientVersion : 1.4.38.0
DirSyncClientMachine : SERVER1
DirSyncFeatures : 41016
DisplayName : Company Ltd
IsDirSyncing : true
IsPasswordSyncing : false
IsTrackingChanges : false
MaxLinksSupportedAcrossBatchInProvision : 15000
PreventAccidentalDeletion : EnabledForCount
SynchronizationInterval : PT30M
TenantId : 57cf9f28-1ad7-40f4-bee8-d3ab9877f0a8
TotalConnectorSpaceObjects : 1
TresholdCount : 500
TresholdPercentage : 0
UnifiedGroupContainer :
UserContainer :
DirSyncAnchorAttribute : mS-DS-ConsistencyGuid
DirSyncServiceAccount : [email protected]
DirectorySynchronizationStatus : Enabled
InitialDomain : company.onmicrosoft.com
LastDirSyncTime : 2020-03-03T10:23:09Z
LastPasswordSyncTime : 2020-03-04T10:23:43Z
ADSyncBlackListEnabled : false
ADSyncBlackList : {1.0}
ADSyncLatestVersion : 3.2
ADSyncMinimumVersion : 1.0
.Example
Get-AADIntSyncConfiguration
ApplicationVersion : 1651564e-7ce4-4d99-88be-0a65050d8dc3
ClientVersion : 1.4.38.0
DirSyncAnchorAttribute : mS-DS-ConsistencyGuid
DirSyncClientMachine : SERVER1
DirSyncServiceAccount : [email protected]
DirectorySynchronizationStatus : Enabled
DisplayName : Company Ltd
InitialDomain : company.onmicrosoft.com
IsDirSyncing : true
LastDirSyncTime : 2020-03-03T10:23:09Z
LastPasswordSyncTime : 2020-03-04T10:23:43Z
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# First get configuration from Provisioning API (no admin rights needed)
$config = Get-CompanyInformation -AccessToken $AccessToken
# Show the warning of the pending state
if($config.DirectorySynchronizationStatus.StartsWith("Pending"))
{
Write-Warning "Synchronization status is $($config.DirectorySynchronizationStatus) and it may be stuck to this state for up to 72h!"
}
# Return value
$attributes=[ordered]@{
ApplicationVersion = $config.DirSyncApplicationType
ClientVersion = $config.DirSyncClientVersion
DirSyncAnchorAttribute = $config.DirSyncAnchorAttribute
DirSyncClientMachine = $config.DirSyncClientMachineName
DirSyncServiceAccount = $config.DirSyncServiceAccount
DirectorySynchronizationStatus = $config.DirectorySynchronizationStatus
DisplayName = $config.DisplayName
InitialDomain = $config.InitialDomain
IsDirSyncing = $config.DirectorySynchronizationEnabled
LastDirSyncTime = $config.LastDirSyncTime
LastPasswordSyncTime = $config.LastPasswordSyncTime
PasswordSynchronizationEnabled = $config.PasswordSynchronizationEnabled
}
# Try to get synchronization information using Azure AD Sync
try
{
$config2=Get-SyncConfiguration2 -AccessToken $AccessToken
# Merge the configs
foreach($key in $attributes.Keys)
{
$config2[$key] = $attributes[$key]
}
$capabilities=Get-SyncCapabilities -AccessToken $AccessToken
# Merge the configs
foreach($key in $capabilities.Keys)
{
$config2[$key] = $capabilities[$key]
}
return New-Object PSObject -Property $config2
}
catch
{
return New-Object PSObject -Property $attributes
}
}
}
# Get synchronization configuration using Sync API
# Oct 11th 2018
function Get-SyncConfiguration2
{
<#
.SYNOPSIS
Gets tenant's synchronization configuration
.DESCRIPTION
Gets tenant's synchronization configuration using Provisioning and Azure AD Sync API.
.Parameter AccessToken
Access Token
.Example
Get-AADIntSyncConfiguration
AllowedFeatures : {ObjectWriteback, , PasswordWriteback}
AnchorAttribute : objectGUID
ApplicationVersion : 1651564e-7ce4-4d99-88be-0a65050d8dc3
ClientVersion : 1.1.819.0
DirSyncClientMachine : AAD-SYNC-01
DirSyncFeatures : 41016
DisplayName : Company Ltd
IsDirSyncing : true
IsPasswordSyncing : false
IsTrackingChanges : false
MaxLinksSupportedAcrossBatchInProvision : 15000
PreventAccidentalDeletion : EnabledForCount
SynchronizationInterval : PT30M
TenantId : 57cf9f28-1ad7-40f4-bee8-d3ab9877f0a8
TotalConnectorSpaceObjects : 24
TresholdCount : 500
TresholdPercentage : 0
UnifiedGroupContainer :
UserContainer :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetCompanyConfiguration xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<includeLicenseInformation>false</includeLicenseInformation>
</GetCompanyConfiguration>
"@
$Message_id=(New-Guid).ToString()
$Command="GetCompanyConfiguration"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-SyncConfiguration -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetCompanyConfigurationResponse.GetCompanyConfigurationResult
$AllowedFeatures = @()
foreach($feature in $res.AllowedFeatures.'#text')
{
$AllowedFeatures += $feature
}
$config=[ordered]@{
AllowedFeatures = $AllowedFeatures
AnchorAttribute = $res.DirSyncConfiguration.AnchorAttribute
ApplicationVersion = $res.DirSyncConfiguration.ApplicationVersion
ClientVersion = $res.DirSyncConfiguration.ClientVersion
DirSyncClientMachine = $res.DirSyncConfiguration.CurrentExport.DirSyncClientMachineName
DirSyncFeatures = $res.DirSyncFeatures
DisplayName = $res.DisplayName
IsDirSyncing = $res.IsDirSyncing
IsPasswordSyncing = $res.IsPasswordSyncing
IsTrackingChanges = $res.DirSyncConfiguration.IsTrackingChanges
MaxLinksSupportedAcrossBatchInProvision = $res.MaxLinksSupportedAcrossBatchInProvision2
PreventAccidentalDeletion = $res.DirSyncConfiguration.PreventAccidentalDeletion.DeletionPrevention
SynchronizationInterval = $res.SynchronizationInterval
TenantId = $res.TenantId
TotalConnectorSpaceObjects = $res.DirSyncConfiguration.CurrentExport.TotalConnectorSpaceObjects
TresholdCount = $res.DirSyncConfiguration.PreventAccidentalDeletion.ThresholdCount
TresholdPercentage = $res.DirSyncConfiguration.PreventAccidentalDeletion.ThresholdPercentage
UnifiedGroupContainer = $res.WriteBack.UnifiedGroupContainer
UserContainer = $res.WriteBack.UserContainer
}
return $config
}
}
}
# Enables or disables Password Hash Sync (PHS)
function Set-PasswordHashSyncEnabled
{
<#
.SYNOPSIS
Enables or disables password hash sync (PHS)
.DESCRIPTION
Enables or disables password hash sync (PHS) using Azure AD Sync API.
If dirsync is disabled, it's first enabled using Provisioning API.
Enabling / disabling the PHS usually takes less than 10 seconds. Check the status using Get-AADIntCompanyInformation.
.Parameter AccessToken
Access Token
.Parameter Enabled
True or False
.Example
Set-AADIntPasswordHashSyncEnabled -Enabled $true
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[Boolean]$Enabled
)
Process
{
Write-Warning "Set-AADIntPasswordHashSyncEnabled is deprecated."
Write-Warning "Use 'Set-AADIntSyncFeatures -EnableFeatures PasswordHashSync' instead."
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get the current feature status
$features = Get-SyncFeatures -AccessToken $AccessToken
# Check whether the PHS sync is already enabled
if($Enabled -and $features.PasswordHashSync)
{
Write-Host "Password Hash Synchronization already enabled"
}
elseif(!$Enabled -and !$features.PasswordHashSync)
{
Write-Host "Password Hash Synchronization already disabled"
}
else
{
# Enable or disable PHS
if($Enabled)
{
$features = Set-SyncFeatures -AccessToken $AccessToken -EnableFeatures PasswordHashSync
if(!$features.PasswordHashSync)
{
Write-Error "Could not enable Password Hash Sync"
}
}
else
{
$features = Set-SyncFeatures -AccessToken $AccessToken -DisableFeatures PasswordHashSync | Out-Null
if($features.PasswordHashSync)
{
Write-Error "Could not disable Password Hash Sync"
}
}
}
}
}
# Set sync features
# Nov 3rd 2021
function Set-SyncFeatures
{
<#
.SYNOPSIS
Enables or disables synchronisation features.
.DESCRIPTION
Enables or disables synchronisation features using Azure AD Sync API.
As such, doesn't require "Global Administrator" credentials, "Directory Synchronization Accounts" credentials will do.
.Parameter AccessToken
Access Token
.Parameter EnableFeatures
List of features to be enabled
.Parameter DisableFeatures
List of features to be disabled
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Set-AADIntSyncFeature -EnableFeatures PasswordHashSync -DisableFeatures BlockCloudObjectTakeoverThroughHardMatch
BlockCloudObjectTakeoverThroughHardMatch : False
BlockSoftMatch : False
DeviceWriteback : False
DirectoryExtensions : False
DuplicateProxyAddressResiliency : True
DuplicateUPNResiliency : True
EnableSoftMatchOnUpn : True
EnableUserForcePasswordChangeOnLogon : False
EnforceCloudPasswordPolicyForPasswordSyncedUsers : False
PassThroughAuthentication : False
PasswordHashSync : True
PasswordWriteBack : False
SynchronizeUpnForManagedUsers : True
UnifiedGroupWriteback : False
UserWriteback : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet('PasswordHashSync','PasswordWriteBack','DirectoryExtensions','DuplicateUPNResiliency','EnableSoftMatchOnUpn','DuplicateProxyAddressResiliency','EnforceCloudPasswordPolicyForPasswordSyncedUsers','UnifiedGroupWriteback','UserWriteback','DeviceWriteback','SynchronizeUpnForManagedUsers','EnableUserForcePasswordChangeOnLogon','PassThroughAuthentication','BlockSoftMatch','BlockCloudObjectTakeoverThroughHardMatch')]
[String[]]$EnableFeatures,
[Parameter(Mandatory=$False)]
[ValidateSet('PasswordHashSync','PasswordWriteBack','DirectoryExtensions','DuplicateUPNResiliency','EnableSoftMatchOnUpn','DuplicateProxyAddressResiliency','EnforceCloudPasswordPolicyForPasswordSyncedUsers','UnifiedGroupWriteback','UserWriteback','DeviceWriteback','SynchronizeUpnForManagedUsers','EnableUserForcePasswordChangeOnLogon','PassThroughAuthentication','BlockSoftMatch','BlockCloudObjectTakeoverThroughHardMatch')]
[String[]]$DisableFeatures
)
Begin
{
$feature_values = [ordered]@{
"PasswordHashSync" = 1
"PasswordWriteBack" = 2
"DirectoryExtensions" = 4
"DuplicateUPNResiliency" = 8
"EnableSoftMatchOnUpn" = 16
"DuplicateProxyAddressResiliency" = 32
# 64
# 128
# 256
"EnforceCloudPasswordPolicyForPasswordSyncedUsers" = 512
"UnifiedGroupWriteback" = 1024
"UserWriteback" = 2048
"DeviceWriteback" = 4096
"SynchronizeUpnForManagedUsers" = 8192
"EnableUserForcePasswordChangeOnLogon" = 16384
# 32768
# 65536
"PassThroughAuthentication" = 131072
# 262144
"BlockSoftMatch" = 524288
"BlockCloudObjectTakeoverThroughHardMatch" = 1048576
}
}
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get the current features
$features = (Get-SyncConfiguration2 -AccessToken $AccessToken).DirSyncFeatures
# Enable features
foreach($feature in $EnableFeatures)
{
$features = $features -bor $feature_values[$feature]
}
# Disable features
foreach($feature in $DisableFeatures)
{
$features = $features -band (0x7FFFFFFF -bxor $feature_values[$feature])
}
Update-SyncFeatures -AccessToken $AccessToken -Features $features
Get-SyncFeatures -AccessToken $AccessToken
}
}
# Get sync features
# Nov 3rd 2021
function Get-SyncFeatures
{
<#
.SYNOPSIS
Show the status of synchronisation features.
.DESCRIPTION
Show the status of synchronisation features using Azure AD Sync API.
As such, doesn't require "Global Administrator" credentials, "Directory Synchronization Accounts" credentials will do.
.Parameter AccessToken
Access Token
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntSyncFeatures
BlockCloudObjectTakeoverThroughHardMatch : True
BlockSoftMatch : False
DeviceWriteback : False
DirectoryExtensions : False
DuplicateProxyAddressResiliency : True
DuplicateUPNResiliency : True
EnableSoftMatchOnUpn : True
EnableUserForcePasswordChangeOnLogon : False
EnforceCloudPasswordPolicyForPasswordSyncedUsers : False
PassThroughAuthentication : False
PasswordHashSync : True
PasswordWriteBack : False
SynchronizeUpnForManagedUsers : True
UnifiedGroupWriteback : False
UserWriteback : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Begin
{
$feature_values = [ordered]@{
"BlockCloudObjectTakeoverThroughHardMatch" = 1048576
"BlockSoftMatch" = 524288
"DeviceWriteback" = 4096
"DirectoryExtensions" = 4
"DuplicateProxyAddressResiliency" = 32
"DuplicateUPNResiliency" = 8
"EnableSoftMatchOnUpn" = 16
"EnableUserForcePasswordChangeOnLogon" = 16384
"EnforceCloudPasswordPolicyForPasswordSyncedUsers" = 512
"PassThroughAuthentication" = 131072
"PasswordHashSync" = 1
"PasswordWriteBack" = 2
"SynchronizeUpnForManagedUsers" = 8192
"UnifiedGroupWriteback" = 1024
"UserWriteback" = 2048
}
}
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get the current features
$features = (Get-SyncConfiguration2 -AccessToken $AccessToken).DirSyncFeatures
$attributes = [ordered]@{}
# Enable features
foreach($key in $feature_values.Keys)
{
$attributes[$key] = ($features -band $feature_values[$key]) -gt 0
}
New-Object psobject -Property $attributes
}
}
# Update dirsync features
# Nov 3rd 2021
function Update-SyncFeatures
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[int]$Features,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<SetCompanyDirsyncFeatures xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<dirsyncFeatures>$Features</dirsyncFeatures>
</SetCompanyDirsyncFeatures>
"@
$Message_id=(New-Guid).ToString()
$Command="SetCompanyDirsyncFeatures"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Set-SyncFeatures -AccessToken $AccessToken -Features $Features -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetCompanyConfigurationResponse.GetCompanyConfigurationResult
}
}
}
# Provision Azure AD Sync Object
function Set-AzureADObject
{
<#
.SYNOPSIS
Creates or updates Azure AD object using Azure AD Sync API
.DESCRIPTION
Creates or updates Azure AD object using Azure AD Sync API. Can also set cloud-only user's sourceAnchor (ImmutableId) and onPremisesSAMAccountName. SourceAnchor can only be set once!
.Parameter AccessToken
Access Token
.Parameter sourceAnchor
The source anchor for the Azure AD object. Typically Base 64 encoded GUID of on-prem AD object.
.Parameter cloudAnchor
The cloud anchor for the Azure AD object in the form "<type>_<objectid>". For example "User_a98368aa-f0cb-41b5-a7c6-10f18c6c837d"
.Parameter userPrincipalName
User Principal Name of the Azure AD object
.Parameter surname
The last name of the Azure AD object
.Parameter onPremisesSamAccountName
The on-prem AD samaccountname of the Azure AD object
.Parameter onPremisesDistinguishedName
The on-prem AD DN of the Azure AD object
.Parameter onPremisesSecurityIdentifier
The on-prem AD security identifier of the Azure AD object
.Parameter netBiosName
The on-prem netbiosname of the Azure AD object
.Parameter lastPasswordChangeTimeStamp
Timestamp when the on-prem AD object's password was changed
.Parameter givenName
The first name of the Azure AD object
.Parameter dnsDomainName
The dns domain name of the Azure AD object
.Parameter displayName
The display name of the Azure AD object
.Parameter countryCode
The country code of the Azure AD object.
.Parameter commonName
The common name of the Azure AD object
.Parameter accountEnabled
Is the Azure AD object enabled. Default is $True.
.Parameter cloudMastered
Is the Azure AD object editable in Azure AD. Default is $true
.Parameter usageLocation
Two letter country code for usage location of Azure AD object.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$CloudAnchor,
[Parameter(Mandatory=$False)]
[String]$SourceAnchor,
[Parameter(Mandatory=$False)]
[String]$userPrincipalName,
[Parameter(Mandatory=$False)]
[String]$surname,
[Parameter(Mandatory=$False)]
[String]$onPremisesSamAccountName,
[Parameter(Mandatory=$False)]
[String]$onPremisesDistinguishedName,
[Parameter(Mandatory=$False)]
[String]$onPremiseSecurityIdentifier,
[Parameter(Mandatory=$False)]
[String]$netBiosName,
[Parameter(Mandatory=$False)]
[String]$lastPasswordChangeTimestamp,
[Parameter(Mandatory=$False)]
[String]$givenName,
[Parameter(Mandatory=$False)]
[String]$dnsDomainName,
[Parameter(Mandatory=$False)]
[String]$displayName,
[Parameter(Mandatory=$False)]
$countryCode,
[Parameter(Mandatory=$False)]
[String]$commonName,
[Parameter(Mandatory=$False)]
$accountEnabled,
[Parameter(Mandatory=$False)]
$cloudMastered,
[Parameter(Mandatory=$False)]
[ValidateSet('AF','AX','AL','DZ','AS','AD','AO','AI','AQ','AG','AR','AM','AW','AU','AT','AZ','BS','BH','BD','BB','BY','BE','BZ','BJ','BM','BT','BO','BQ','BA','BW','BV','BR','IO','BN','BG','BF','BI','KH','CM','CA','CV','KY','CF','TD','CL','CN','CX','CC','CO','KM','CG','CD','CK','CR','CI','HR','CU','CW','CY','CZ','DK','DJ','DM','DO','EC','EG','SV','GQ','ER','EE','ET','FK','FO','FJ','FI','FR','GF','PF','TF','GA','GM','GE','DE','GH','GI','GR','GL','GD','GP','GU','GT','GG','GN','GW','GY','HT','HM','VA','HN','HK','HU','IS','IN','ID','IQ','IE','IR','IM','IL','IT','JM','JP','JE','JO','KZ','KE','KI','KP','KR','KW','KG','LA','LV','LB','LS','LR','LY','LI','LT','LU','MO','MK','MG','MW','MY','MV','ML','MT','MH','MQ','MR','MU','YT','MX','FM','MD','MC','MN','ME','MS','MA','MZ','MM','NA','NR','NP','NL','NC','NZ','NI','NE','NG','NU','NF','MP','NO','OM','PK','PW','PS','PA','PG','PY','PE','PH','PN','PL','PT','PR','QA','RE','RO','RU','RW','BL','SH','KN','LC','MF','PM','VC','WS','SM','ST','SA','SN','RS','SC','SL','SG','SX','SK','SI','SB','SO','ZA','GS','SS','ES','LK','SD','SR','SJ','SZ','SE','CH','SY','TW','TJ','TZ','TH','TL','TG','TK','TO','TT','TN','TR','TM','TC','TV','UG','UA','AE','GB','US','UM','UY','UZ','VU','VE','VN','VG','VI','WF','EH','YE','ZM','ZW')][String]$usageLocation,
[Parameter(Mandatory=$False)]
[ValidateSet('User','Group','Contact','Device')]
[String]$ObjectType="User",
[Parameter(Mandatory=$False)]
[String[]]$proxyAddresses,
[Parameter(Mandatory=$False)]
[String]$thumbnailPhoto,
[Parameter(Mandatory=$False)]
[String[]]$groupMembers,
[Parameter(Mandatory=$False)]
[String]$deviceId,
[Parameter(Mandatory=$False)]
[String]$deviceOSType,
[Parameter(Mandatory=$False)]
[String]$deviceTrustType,
[Parameter(Mandatory=$False)]
[String[]]$userCertificate,
[Parameter(Mandatory=$False)]
[ValidateSet('Set','Add')]
[String]$Operation="Set",
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<ProvisionAzureADSyncObjects xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<syncRequest xmlns:b="http://schemas.microsoft.com/online/aws/change/2014/06" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:SyncObjects>
<b:AzureADSyncObject>
<b:PropertyValues xmlns:c="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
$(Add-PropertyValue "SourceAnchor" $sourceAnchor)
$(Add-PropertyValue "accountEnabled" $accountEnabled -Type bool)
$(Add-PropertyValue "commonName" $commonName)
$(Add-PropertyValue "countryCode" $countryCode -Type long)
$(Add-PropertyValue "displayName" $displayName)
$(Add-PropertyValue "dnsDomainName" $dnsDomainName)
$(Add-PropertyValue "givenName" $givenName)
$(Add-PropertyValue "lastPasswordChangeTimestamp" $lastPasswordChangeTimestamp)
$(Add-PropertyValue "netBiosName" $netBiosName)
$(Add-PropertyValue "onPremiseSecurityIdentifier" $onPremiseSecurityIdentifier -Type base64)
$(Add-PropertyValue "onPremisesDistinguishedName" $onPremisesDistinguishedName)
$(Add-PropertyValue "onPremisesSamAccountName" $onPremisesSamAccountName)
$(Add-PropertyValue "surname" $surname)
$(Add-PropertyValue "userPrincipalName" $userPrincipalName)
$(Add-PropertyValue "cloudMastered" $cloudMastered -Type bool)
$(Add-PropertyValue "usageLocation" $usageLocation)
$(Add-PropertyValue "CloudAnchor" $CloudAnchor)
$(Add-PropertyValue "ThumbnailPhoto" $thumbnailPhoto)
$(Add-PropertyValue "proxyAddresses" $proxyAddresses -Type ArrayOfstring)
$(Add-PropertyValue "member" $groupMembers -Type ArrayOfstring)
$(Add-PropertyValue "deviceId" $deviceId -Type base64)
$(Add-PropertyValue "deviceTrustType" $deviceTrustType)
$(Add-PropertyValue "deviceOSType" $deviceOSType)
$(Add-PropertyValue "userCertificate" $userCertificate -Type ArrayOfbase64)
$(if($ObjectType -eq "User"){Add-PropertyValue "userType" $userType})
$(if($ObjectType -eq "Group"){Add-PropertyValue "securityEnabled" $true -Type bool})
</b:PropertyValues>
<b:SyncObjectType>$ObjectType</b:SyncObjectType>
<b:SyncOperation>$Operation</b:SyncOperation>
</b:AzureADSyncObject>
</b:SyncObjects>
</syncRequest>
</ProvisionAzureADSyncObjects>
"@
$Message_id=(New-Guid).ToString()
$Command="ProvisionAzureADSyncObjects"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Set-AzureADObject -AccessToken $AccessToken -Recursion ($Recursion+1) -sourceAnchor $sourceAnchor -ObjectType $ObjectType -userPrincipalName $userPrincipalName -surname $surname -onPremisesSamAccountName $onPremisesSamAccountName -onPremisesDistinguishedName $onPremisesDistinguishedName -onPremiseSecurityIdentifier $onPremisesDistinguishedName -netBiosName $netBiosName -lastPasswordChangeTimestamp $lastPasswordChangeTimestamp -givenName $givenName -dnsDomainName $dnsDomainName -displayName $displayName -countryCode $countryCode -commonName $commonName -accountEnabled $accountEnabled -cloudMastered $cloudMastered -usageLocation $usageLocation -CloudAnchor $CloudAnchor
}
# Check whether this is an error message
if($xml_doc.Envelope.Body.Fault)
{
Throw $xml_doc.Envelope.Body.Fault.Reason.Text.'#text'
}
# Return
$xml_doc.Envelope.Body.ProvisionAzureADSyncObjectsResponse.ProvisionAzureADSyncObjectsResult.SyncObjectResults.AzureADSyncObjectResult
}
}
# Removes the given Azure AD Object
function Remove-AzureADObject
{
<#
.SYNOPSIS
Removes Azure AD object using Azure AD Sync API
.DESCRIPTION
Removes Azure AD object using Azure AD Sync API
.Parameter AccessToken
Access Token
.Parameter sourceAnchor
The source anchor for the Azure AD object. Typically Base 64 encoded GUID of on-prem AD object.
.Parameter cloudAnchor
The cloud anchor for the Azure AD object in the form "<type>_<objectid>". For example "User_a98368aa-f0cb-41b5-a7c6-10f18c6c837d"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='sourceAnchor', Mandatory=$True)]
[String]$sourceAnchor,
[Parameter(ParameterSetName='cloudAnchor', Mandatory=$True)]
[String]$cloudAnchor,
[Parameter(Mandatory=$False)]
[ValidateSet('User','Group','Contact','Device')]
[String]$ObjectType="User",
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<ProvisionAzureADSyncObjects xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<syncRequest xmlns:b="http://schemas.microsoft.com/online/aws/change/2014/06" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:SyncObjects>
<b:AzureADSyncObject>
<b:PropertyValues xmlns:c="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
$(Add-PropertyValue "SourceAnchor" $sourceAnchor)
$(Add-PropertyValue "CloudAnchor" $cloudAnchor)
</b:PropertyValues>
<b:SyncObjectType>$ObjectType</b:SyncObjectType>
<b:SyncOperation>Delete</b:SyncOperation>
</b:AzureADSyncObject>
</b:SyncObjects>
</syncRequest>
</ProvisionAzureADSyncObjects>
"@
$Message_id=(New-Guid).ToString()
$Command="ProvisionAzureADSyncObjects"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Remove-AzureADObject -AccessToken $AccessToken -Recursion ($Recursion+1) -sourceAnchor $sourceAnchor -ObjectType $ObjectType
}
# Return
$xml_doc.Envelope.Body.ProvisionAzureADSyncObjectsResponse.ProvisionAzureADSyncObjectsResult.SyncObjectResults.AzureADSyncObjectResult
}
}
# Finalize Azure AD Sync
function Finalize-Export
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Count=1,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<FinalizeExport xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<totalExported>$count</totalExported>
<successfulExportCount>$count</successfulExportCount>
</FinalizeExport>
"@
$Message_id=(New-Guid).ToString()
$Command="FinalizeExport"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Parse-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Finalize-Export -Count $Count -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
return $xml_doc
}
}
}
# Get sync objects from Azure AD
function Get-SyncObjects
{
<#
.SYNOPSIS
Gets tenant's synchronized objects
.DESCRIPTION
Gets tenant's synchronized objects using Azure AD Sync API
.Parameter AccessToken
Access Token
.Parameter Version
Version number of AD Sync, defaults to 2. Version 2 returns only non-empty attributes and is thus much more efficient.
.Example
Get-AADIntSyncObjects -AccessToken $at -Version 1
AccountEnabled : true
Alias :
City :
CloudAnchor : User_64c6616b-f961-4882-a03e-9209d01711aa
CloudLegacyExchangeDN : /o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=7e07ff8b-5d1c-4319-b608-c371914fbd99-Megan Bowen
CloudMSExchArchiveStatus :
CloudMSExchBlockedSendersHash :
CloudMSExchRecipientDisplayType : 1073741824
CloudMSExchSafeRecipientsHash :
CloudMSExchSafeSendersHash :
CloudMSExchTeamMailboxExpiration :
CloudMSExchTeamMailboxSharePointUrl :
CloudMSExchUCVoiceMailSettings :
CloudMSExchUserHoldPolicies :
CloudMastered : false
CommonName : Megan Bowen
Company :
Country :
CountryCode : 0
CountryLetterCode :
Department :
Description :
DisplayName : Megan Bowen
DnsDomainName : company.com
...
.Example
Get-AADIntSyncObjects -AccessToken $at
AccountEnabled : true
CloudAnchor : User_64c6616b-f961-4882-a03e-9209d01711aa
CloudLegacyExchangeDN : /o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=7e07ff8b-5d1c-4319-b608-c371914fbd99-Megan Bowen
CloudMSExchRecipientDisplayType : 1073741824
CloudMastered : false
CommonName : Megan Bowen
CountryCode : 0
DisplayName : Megan Bowen
DnsDomainName : company.com
GivenName : Megan
LastPasswordChangeTimestamp : 20190801164342.0Z
NetBiosName : COMPANY
OnPremiseSecurityIdentifier :
OnPremisesDistinguishedName : CN=Megan Bowen,OU=Domain Users,DC=company,DC=com
OnPremisesSamAccountName : MeganB
SourceAnchor :
Surname : Bowen
SyncObjectType : User
SyncOperation : Set
UsageLocation : US
UserPrincipalName : [email protected]
UserType : Member
#>
[cmdletbinding()]
Param(