다음을 통해 공유


Active Directory On-Premises to Windows Azure Active Directory Windows PowerShell Script

Summary

This script enables you to migrate your enterprise AD from purely an on-premise AD to a federated AD and linking your on-prem AD with the AD in Azure. This script is run on both your ADFS servers, and your ADFS-Proxy servers. The script displays a menu of the tasks needed to install and configure yoru ADFS and ADFS-Proxy Servers.

Using this Script

You can copy the script, contained in the box below, onto your ADFS and ADFS Proxies systems - either saving them as a file, or pasting into the PowerShell ISE. You then run the script. The script displays a menu of the tasks required to migrate to implement ADFS and ADFS Proxy systems in your enterprise. You select the item, and the script performs the actions.

You can of course modify the script, but please, only do so after you test and verify your changes. You can also edit this Wiki page and share your changes. If sharing yhour changes, make notes as to what you did to the script when saving changes, so people can go back and look at the history of the changes and pick the version that is correct for them. If you make major changes, consider posting it to a different TechNet Wiki article and/or on the TechNet Script Center.

Notes

This is a community version of the Windows PowerShell script that was originally posted on the TechNet Script Center. You can download that unmodified version from Technet, or make use of the community updates as posted here.

Opportunities for Modifying this script

All scripts can be improved. Some modifications that would be useful for this script include:

  1. Give the user the ability to utilize an existing SSL certificate, instead of a self-signed certificate
  2. Provide more verbose instructions in the script such that the Quickstart guide is not needed in order to run the script
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
#Requires –Version 2.0
#=================================================================================
# Community version of a script originated by DavidTest http://about.me/DavidTesar
#=================================================================================

#region ----- script-level variables -----

Set-Variable -Name CurrentExecutingPath -Scope 'script' -Option 'ReadOnly'-Value (Split-Path $MyInvocation.MyCommand.Definition)

Set-Variable -Name CertificateFriendlyName -Scope 'script' -option 'ReadOnly' -Value 'AD to AAD QuickStart ADFS Certificate'

$script:ADFSDomainName = $null
$script:ADFSAccountName = $null
$script:ADFSAccountPassword = $null
$script:ADFSSubjectName = $null
$script:ADFSSubjectDomainName = $null
$script:ADFSCredentials = $null

$script:MsolCredential = $null

$script:ADFSSite = $null

$script:MSOLConnected = $false

$script:CertificateFileName = $script:CurrentExecutingPath + '\ADFSSelfSigned.pfx'

# http://msdn.microsoft.com/en-us/library/aa374830.aspx
$script:AltNameType = @{
DNS_NAME = 3 # A Domain Name System (DNS) name such as MyDomain.Microsoft.com.
IP_ADDRESS = 8 # An Internet Protocol (IP) address in dotted decimal format 123.456.789.123.
}

#endregion

#region ----- support functions -----

function Write-QSCompletionMessage {
Write-Host ''
Write-Host 'Completed. Press "Enter" to continue.'
Read-Host
Write-Host ''
}

# Writes an error message to the host
function Write-QSError {
param (
[Parameter(Mandatory=$true, HelpMessage="The error message.")]
[string] $Message
)
#Write-Error $Message
Write-Host ''
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Red' $Message
Write-Host ''
}

# Writes a warning message to the host
function Write-QSWarning {
param (
[Parameter(Mandatory=$true, HelpMessage="The warning message.")]
[string] $Message
)
Write-Host ''
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Yellow' $Message
Write-Host ''
}

# Returns $true if the current execution environment is elevated.
function Get-QSElevationStatus {
$wid = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp = New-Object System.Security.Principal.WindowsPrincipal($wid)
$adm = [System.Security.Principal.WindowsBuiltInRole]::Administrator
$IsAdmin = $prp.IsInRole($adm)
return $IsAdmin
}

# Is this a 32-bit process on a 64-bit system?
function Test-QSWow64() {
    return (Test-QSWin32) -and (Test-Path env:\PROCESSOR_ARCHITEW6432)
}

# Is this a 64 bit process?
function Test-QSWin64() {
    return [IntPtr]::size -eq 8
}

# Is this a 32 bit process?
function Test-QSWin32() {
    return [IntPtr]::size -eq 4
}

# Is this a server OS SKU?
function Test-QSServerOS() {
return ((Get-WmiObject Win32_OperatingSystem).ProductType -ne 1)
}

# Is this server 2012/Windows 8 or later?
function Test-QSWindows8OrLater() {
return ((Get-WmiObject Win32_OperatingSystem).Version -ge (New-Object System.Version(6,2,0,0)))
}

# Writes a nicely formatted title for an area.
function Write-QSTitle {
param (
[Parameter(Mandatory=$true, HelpMessage='The title of the current area.')]
[string] $Title,
[Parameter(Mandatory=$false, HelpMessage='Indicates a double dashed line should be used.')]
[switch] $DoubleDashedLine
)
$DashedLine = '-' * ($Title.Length + 10)
Write-Host ''
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Yellow' $DashedLine
if ($DoubleDashedLine) {
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Yellow' $DashedLine
}
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Yellow' " $Title "
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Yellow' $DashedLine
if ($DoubleDashedLine) {
Write-Host -BackgroundColor 'Black' -ForegroundColor 'Yellow' $DashedLine
}
Write-Host ''
}

# asks the user for an item from a list
function Read-QSListChoice {
param (
[Parameter(Mandatory=$true, HelpMessage='The list of choices.')]
[string[]] $Choices,
[Parameter(Mandatory=$true, HelpMessage='The title for the choice.')]
[string] $Title,
[Parameter(Mandatory=$true, HelpMessage='The user prompt for the choice.')]
[string] $Prompt
)
if ($Choices.Count -eq 0) {
return $null
}
if ($Choices.Count -eq 1) {
return $Choices[0]
}
Write-Host ' '
Write-Host $Title
Write-Host ' '
Write-Host ' 0) NONE'
for ($Counter = 0; $Counter -lt $Choices.Count; $Counter++) {
Write-Host ('{0,2}) {1}' -f ($Counter + 1), $Choices[$Counter])
}
Write-Host ''
$Choice = Read-Host $Prompt
if ($Choice -eq 0) {
Write-QSWarning 'Cancelled.'
return $null
}
return $Choices[$Choice-1]
}

function Require-QSDownloadableFile {
param (
[Parameter(Mandatory=$true, HelpMessage='The name of the file that should be downloaded if it is not present.')]
[string] $FileName,
[Parameter(Mandatory=$true, HelpMessage='The URL source for the file for downloading if it is not present.')]
[string] $URL
)
if ((Test-Path "$Filename") -ne $true) {
Write-Host "Downloading $Filename`n from $URL`n please wait..."
$webClient = New-Object System.Net.WebClient
try {
$webClient.DownloadFile($url, "$Filename")
Unblock-File -Path "$Filename"
}
catch {
return $false
}
}
$true
}

function Require-QSLocalFile {
param (
[Parameter(Mandatory=$true, HelpMessage='The name of the file that should be present.')]
[string] $FileName
)
if ((Test-Path $Filename) -ne $true) {
Write-QSError "Required local file not present: $Filename"
return $false
}
$true
}

function Require-QSProduct {
param (
[Parameter(Mandatory=$true, HelpMessage='The display name of the MSI package as shown in "Add/Remove Programs".')]
[string] $DisplayName,
[Parameter(Mandatory=$true, HelpMessage='The filename for the MSI source for the installation')]
[string] $FileName,
[Parameter(Mandatory=$true, HelpMessage='The download URL for the MSI if it is not available locally.')]
[string] $URL
)
Write-Host "Checking to see if machine already has product $DisplayName installed..."
$Product = Get-WmiObject -Class Win32_Product -ComputerName . | Where-Object -FilterScript { $_.Name -eq $DisplayName }
if ($Product -eq $null) {
$MSIFilename = $script:CurrentExecutingPath + "\$FileName"
if (Require-QSDownloadableFile -url $URL -filename $MSIFilename) {
Write-Host "Installing MSI $MSIFilename`n please wait..."
$ExitCode = (Start-Process -Wait -PassThru -FilePath msiexec -ArgumentList /i, $msiFilename, /qb, /l*vx, $env:TEMP\$FileName.txt).ExitCode
if ($ExitCode -eq 0) {
Write-Host 'Installation complete.'
return $true
} else {
Write-Error "FAILURE ON INSTALL: $ExitCode"
return $false
}
} else {
Write-Error "Could not download $MSIFilename from $URL"
return $false
}
} else {
Write-Host 'Product is already installed, will not reinstall.'
return $true
}
}

Function Require-QSModule {
param (
[Parameter(Mandatory=$true, HelpMessage='Name of the PowerShell module that is required.')]
[string] $Name,
[Parameter(Mandatory=$false, HelpMessage='Return a status code of false rather than failing if not found.')]
[switch] $PoliteCheck
)
if (-not (Get-Module -name $Name)) { 
Write-Host "Attempting to load system module $Name" -ErrorAction 'SilentlyContinue'
Import-Module -Name $Name -ErrorAction 'SilentlyContinue'
$Results = $?
if ($PoliteCheck) {
return $Results
} else {
Test-QSRequirement -Requirement $Results -Message "Could not load required PowerShell module $Name."
}
}
if ($PoliteCheck) {
return $true
}
}

# Ensures a feature is installed on the local machine.
function Require-QSWindowsFeature {
param (
[Parameter(Mandatory=$true, HelpMessage='The name of the Windows feature that is required.')]
[string] $FeatureName
)
if ((Get-WindowsFeature $FeatureName).Installed -eq $false) {
Write-Host "Local Windows Feature $FeatureName missing, installing..."
$InstallResult = Install-WindowsFeature $FeatureName
Test-QSRequirement -Requirement $InstallResult.Success -Message "Required Windows feature $FeatureName failed to install."
}
}

# Runs a command and waits for it to exit
function Invoke-QSCommand() {
    param (
[Parameter(Mandatory=$true, HelpMessage='The name of the executable to execute.')]
[string] $Program,
[Parameter(Mandatory=$false, HelpMessage='The arguments to the command.')]
        [string] $ArgumentString = ''
)

    $psi = New-Object 'Diagnostics.ProcessStartInfo'
    $psi.FileName = $Program 
    $psi.Arguments = $ArgumentString
$psi.RedirectStandardError = $false
$psi.RedirectStandardOutput = $false
    $proc = [Diagnostics.Process]::Start($psi)
    $proc.WaitForExit();
}

# gets the list of UPN suffixes for the current forest
function Get-QSDomainSuffixes {
Require-QSWindowsFeature RSAT-AD-Powershell
Require-QSModule ActiveDirectory
$Domain = Get-ADDomain
$DomainDN = $Domain.distinguishedName
$UPNDN = "cn=Partitions,cn=Configuration,$domaindn"            
$UPNSuffixes = Get-ADObject -Identity $UPNDN -Properties upnsuffixes | Foreach-Object { $_.upnsuffixes }
if ($UPNSuffixes -eq $null) {
$UPNSuffixes = @( $Domain.DNSRoot )
} else {
if ($UPNSuffixes.count -eq 1) {
$UPNSuffixes = @($UPNSuffixes)
}
$UPNSuffixes += $Domain.DNSRoot
}
return $UPNSuffixes
}

# Checks a local requirement based on the boolean passed in and reports an error and exits if the requirement is
# not met.
function Test-QSRequirement {
param (
[Parameter(Mandatory=$true, HelpMessage='Requirement that is being checked that must be $true.')]
[boolean] $Requirement,
[Parameter(Mandatory=$true, HelpMessage='The message to present to the user if the requirement is not met.')]
[string] $Message


if (-not $Requirement) {
Write-QSError $Message
Write-Host 'Cannot continue - exiting.'
Exit
}
}

# Installs the sign-in assistant
function Install-QSSignInAssistant {
return Require-QSProduct -URL 'http://go.microsoft.com/fwlink/p/?linkid=236300' -FileName 'msoidcrl.msi' -DisplayName 'Microsoft Online Services Sign-in Assistant'
}

# Installs the MSOL PowerShell module MSI
function Install-QSMsolServicesModule {
Require-QSWindowsFeature Net-Framework-Core
Require-QSWindowsFeature PowerShell-V2
$InstallResults = Install-QSSignInAssistant
Test-QSRequirement -Requirement $InstallResults -Message 'Cannot install MSOL PowerShell without Sign-In Assistant'
return Require-QSProduct -URL 'http://go.microsoft.com/fwlink/p/?linkid=236297' -FileName 'AdministrationConfig-en.msi' -DisplayName 'Microsoft Online Services Module for Windows PowerShell'
}

# Require we have an active MSOL connection.
function Require-QSActiveMsolConnection {
if ($script:MSOLConnected) {
return
}
if (-not (Require-QSModule -Name MSOnline -PoliteCheck)) {
Write-Host 'The required Microsoft Online Services Module for Windows PowerShell is not installed. It will be installed now.'
Test-QSRequirement -Requirement (Install-QSMsolServicesModule) -Message 'Required module did not install, so script cannot continue.'
Require-QSModule -Name MSOnline
}
Write-Host 'Checking for connection to Microsoft Online Services...'
$script:MSOLConnected = $false
while (-not $script:MSOLConnected) {
$MSOLDomains = Get-MsolDomain -ErrorAction 'SilentlyContinue'
if($?) {
     $script:MSOLConnected = $true
} else {
Write-Host 'Getting credentials for connecting to Microsoft Online Services tenant.'
$script:MsolCredential = $null
$script:MsolCredential = Get-Credential -ErrorAction 'SilentlyContinue' -Message 'Microsoft Online Services Administrator'
Test-QSRequirement -Requirement ($script:MsolCredential -ne $null) -Message 'Credential entry cancelled.'
Connect-MsolService -Credential $script:MsolCredential
}
}
}

# Gets the list of all unverified domains.
function Get-QSUnverifiedDomains {
Require-QSActiveMsolConnection
Write-Host 'Getting unverified domain list...'
return (Get-MsolDomain | Where-Object { $_.Status -ne 'Verified' })
}

# Gets the list of all verified domains that are custom domains.
function Get-QSCustomDomains {
Require-QSActiveMsolConnection
Write-Host 'Getting custom domain list...'
return (Get-MsolDomain | Where-Object { -not ( $_.Name -like '*.onmicrosoft.com' ) } )
}

# Asks the user for a password with confirmation
function Read-QSHostConfirmedPassword {
while (1) {
$Password = Read-Host ' Password' -AsSecureString
$Confirm  = Read-Host 'Confirm password' -AsSecureString
if ((ConvertFrom-QSSecureStringToPlaintext $Password) -eq (ConvertFrom-QSSecureStringToPlaintext $Confirm)) {
return $Password
}
Write-QSWarning 'Passwords did not match, try again.'
}
}

# Converts a secure string to a plaintext string
function ConvertFrom-QSSecureStringToPlaintext {
param (
[Parameter(Mandatory=$true, HelpMessage='The secure string to convert back to plaintext.')]
[System.Security.SecureString] $SecureString
)

return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString))
}

# gets a yes-no answer from the user
function Read-QSHostYesNo {
param (
[Parameter(Mandatory=$true, HelpMessage='The title for the yes/no question.')]
[string] $Title,
[Parameter(Mandatory=$true, HelpMessage='The prompt for the yes/no question.')]
[string] $Prompt,
[Parameter(Mandatory=$true, HelpMessage='The description of what "yes" means.')]
[string] $YesDescription,
[Parameter(Mandatory=$true, HelpMessage='The description of what "no" means.')]
[string] $NoDescription,
[Parameter(Mandatory=$false, HelpMessage='Indicates the default choice should be "yes".')]
[switch] $YesDefault
)
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", $YesDescription
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No", $NoDescription
$Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No)
if ($YesDefault) {
$DefaultValue = 0
} else {
$DefaultValue = 1
}
$Result = $Host.UI.PromptForChoice($Title, $Prompt, $Options, $DefaultValue)
return ($Result -eq 0)
}

# Reads generic credentials with confirmed password
function Read-QSHostCredentials {
param (
[Parameter(Mandatory=$false, HelpMessage='Indicates a domain name should be requested for the account.')]
[switch] $NeedDomainName,
[Parameter(Mandatory=$true, HelpMessage='Indicates the user-visible purpose for the account.')]
[string] $Purpose
)
$DomainName = $null
if ($NeedDomainName) {
$DomainName = Read-Host "Domain name for $Purpose"
if (($DomainName -eq $null) -or ($DomainName -eq '')) {
Write-QSWarning 'Cancelled.'
return $null
}
}
$AccountName = Read-Host "SAM account name for $Purpose"
if (($AccountName -eq $null) -or ($AccountName -eq '')) {
Write-QSWarning 'Cancelled.'
return $null
}
$AccountPassword = Read-QSHostConfirmedPassword
if ((ConvertFrom-QSSecureStringToPlaintext $AccountPassword) -eq '') {
Write-QSWarning 'Cancelled.'
return $null
}
return New-Object Object | `
Add-Member -PassThru -MemberType 'NoteProperty' -Name 'Domain'   -Value $DomainName | `
Add-Member -PassThru -MemberType 'NoteProperty' -Name 'Account'  -Value $AccountName | `
Add-Member -PassThru -MemberType 'NoteProperty' -Name 'Password' -Value $AccountPassword
}

# Gets ADFS service account credentials from the user
function Read-QSHostADFSServiceCredentials {
if ($script:ADFSCredentials -ne $null) {
if (Read-QSHostYesNo -Title 'Existing Credentials' `
-Prompt "You have previously supplied credentials for ADFS service use, use the same ones?" `
-YesDefault `
-NoDescription 'No, supply new credentials' `
-YesDescription 'Yes, use previously supplied credentials') {
return $true
}
}
$Credentials = Read-QSHostCredentials -NeedDomainName -Purpose 'ADFS service account'
if ($Credentials -eq $null) {
return $false
}
$script:ADFSDomainName = $Credentials.Domain
$script:ADFSAccountName = $Credentials.Account
$script:ADFSAccountPassword = $Credentials.Password
$script:ADFSCredentials =  New-Object System.Management.Automation.PSCredential("$script:ADFSDomainName\$script:ADFSAccountName", $script:ADFSAccountPassword)
$true
}

# Gets a domain name from the verified list
function Read-QSHostDomainChoice {
Require-QSActiveMsolConnection
$Domains = Get-QSCustomDomains | Foreach-Object { $_.Name }
if ($Domains.Count -eq 0) {
Write-Error 'No verified custom domains exist in the tenant.'
return $null
}
Read-QSListChoice -Choices $Domains -Prompt 'Domain to use' -Title 'Select a verified domain'
}

# Gets a web site from the local list
function Read-QSWebSite {
Require-QSModule WebAdministration
$Sites = @(Get-Website | Foreach-Object { $_.Name })
if ($Sites.Count -eq 0) {
Write-Error 'No web sites exist on the current machine.'
return $null
}
return Read-QSListChoice -Choices $Sites -Prompt 'IIS site to host the ADFS Proxy' 'Select a web site'
}

# Determines the ADFS subject name
function Require-QSADFSSubjectName {
if ($script:ADFSSubjectName -eq $null) {
$Domain = Read-QSHostDomainChoice
if ($Domain -eq $null) {
return $false
}
$script:ADFSSubjectDomainName = $Domain
$script:ADFSSubjectName = "adfs.$Domain"
}
$true
}

# removes a COM object reference
function Release-QSCOMObject {
param (
[Parameter(Mandatory=$true, HelpMessage='The object to release.')]
[object] $Object

[void] [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Object)
}

# gets the local ADFS certificate and validates it
function Get-QSADFSCertificate {
param (
[Parameter(Mandatory=$false, HelpMessage='Indicates no error should be reported if there is no certificate.')]
[switch] $Silent,
[Parameter(Mandatory=$false, HelpMessage='Indicates verification is unnecessary.')]
[switch] $SkipVerification

$PossibleCertificates = @(Get-ChildItem 'Cert:\LocalMachine\My' | Where-Object { $_.FriendlyName -eq $script:CertificateFriendlyName} )
if ($PossibleCertificates.GetLength(0) -eq 0) {
if (-not $Silent) {
Write-QSError "Expected certficate with friendly name `"$script:CertificateFriendlyName`" not found."
}
return $null
}
if ($PossibleCertificates.GetLength(0) -gt 1) {
Write-QSWarning "More than one certficate with friendly name `"$script:CertificateFriendlyName`" exists.`nSelecting the first one."
}
$PossibleCertificate = $PossibleCertificates[0]
if (-not $SkipVerification) {
if (-not (Require-QSADFSSubjectName)) {
return $null
}
if (-not ($PossibleCertificate.Subject.Contains("CN=$script:ADFSSubjectName"))) {
Write-QSError "The certificate does not have the expected subject of `"CN=$script:ADFSSubjectName`". It cannot be used."
return $null
}
if ($PossibleCertificate.NotBefore -gt (Get-Date)) {
Write-QSError 'The certificate is not yet valid. It cannot be used.'
return $null
}
if ($PossibleCertificate.NotAfter -lt (Get-Date)) {
Write-QSError 'The certificate has expired. It cannot be used.'
return $null
}
if (-not ($PossibleCertificate.HasPrivateKey)) {
Write-QSError "The certificate's private key is not present on this machine. The certificate cannot be used."
return $null
}
if (-not ($PossibleCertificate.Verify())) {
Write-QSError 'The certificate fails verification; this likely means a missing trusted root or intermediate CA. The certificate cannot be used. '
return $null
}
}
return $PossibleCertificate
}

# get the verification value for a specific domain
function Get-QSMsolDNSVerificationText {
param (
[Parameter(Mandatory=$true, HelpMessage='The domain name to query.')]
[object] $Domain

return (Get-MsolDomainVerificationDns -DomainName $Domain ).Label.Split('.')[0]
}

# get a DNS server address
function Read-QSHostDNSServerAddress {
$DNSServerList = @()
$Adapters = ([System.Net.NetworkInformation.NetworkInterface])::GetAllNetworkInterfaces()
foreach ($Adapter in $Adapters) {
$AdapterDNSServers = $Adapter.GetIPProperties().DnsAddresses
foreach ($AdapterDNSServer in $AdapterDNSServers) {
$DNSIP = $AdapterDNSServer.IPAddressToString
if ($DNSIP -match '^.*\..*\..*\..*$') {
if (-not ($DNSServerList -contains $DNSIP)) {
$DNSServerList += $DNSIP
}
}
}
}
if ($DNSServerList.Count -eq 0) {
Write-Warning 'This machine does not appear to be a DNS client.'
return $null;
}
return Read-QSListChoice -Choices $DNSServerList -Title 'Select a DNS server for the creation request' -Prompt 'DNS server'
}

# Require the given key name
function Require-QSRegistryKey {
param (
[Parameter(Mandatory=$true, HelpMessage='The key that is required.')]
[string] $KeyName
)
if (-not (Test-Path $KeyName)) {
$Created = New-Item -Path $KeyName -Type Directory -Force
if ($?) {
return $true
} else {
return $false
}
}
return $false
}

# Require the given key name
function Require-QSRegistryValue {
param (
[Parameter(Mandatory=$true, HelpMessage='The value name that is required.')]
[string] $Name,
[Parameter(Mandatory=$true, HelpMessage='The parent key.')]
[string] $Key,
[Parameter(Mandatory=$true, HelpMessage='The required value.')]
[string] $Value,
[Parameter(Mandatory=$false, HelpMessage='The type of the value.')]
[string] $PropertyType = 'String'
)
$Set = Require-QSRegistryKey -KeyName $Key
if ((Get-ItemProperty -Path $Key -Name $Name -ErrorAction 'SilentlyContinue') -eq $null) {
$Created = New-ItemProperty -Path $Key -PropertyType $PropertyType -Name $Name -Value $Value
return $true
} else {
if ((Get-ItemProperty $Key -Name $Name).$Name -eq $Value) {
return $false
}
$Reset = Set-ItemProperty -Path $Key -PropertyType $PropertyType -Name $Name -Value $Value
return $true
}
}

function Disable-QSInternetExplorerESC {
$DidIt = $false
if (Require-QSRegistryValue -Key 'HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}' -Name 'IsInstalled' -Value 0) {
$DidIt = $true
    Write-Host 'IE Enhanced Security Configuration (ESC) has been disabled for Administrators.' -ForegroundColor Green
}
if (Require-QSRegistryValue -Key 'HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}' -Name 'IsInstalled' -Value 0) {
$DidIt = $true
    Write-Host 'IE Enhanced Security Configuration (ESC) has been disabled for Users.' -ForegroundColor Green
}
if ($DidIt) {
     Stop-Process -Name Explorer
Start-Process -FilePath Explorer
Write-Host 'Restarted Windows Explorer to complete IE ESC configuration.'
}
}

function Configure-QSIISAuthentication {
Require-QSADFSSubjectName 
if ($script:ADFSSite -eq $null) {
$script:ADFSSite = Read-QSWebSite
if ($script:ADFSSite -eq $null) {
return $false
}
}

Write-Host 'Configuring Windows Authentication provider order in IIS...'
Invoke-QSCommand -Program "$env:SystemRoot\system32\inetsrv\appcmd.exe" -ArgumentString "set config '$script:ADFSSite/adfs/ls' -section:system.webServer/security/authentication/windowsAuthentication /enabled:true /commit:apphost"
Invoke-QSCommand -Program "$env:SystemRoot\system32\inetsrv\appcmd.exe" -ArgumentString "set config '$script:ADFSSite/adfs/ls' -section:system.webServer/security/authentication/windowsAuthentication /~providers /commit:apphost"
Invoke-QSCommand -Program "$env:SystemRoot\system32\inetsrv\appcmd.exe" -ArgumentString "set config '$script:ADFSSite/adfs/ls' -section:system.webServer/security/authentication/windowsAuthentication /+`"providers.[value='NTLM']`" /commit:apphost"
Invoke-QSCommand -Program "$env:SystemRoot\system32\inetsrv\appcmd.exe" -ArgumentString "set config '$script:ADFSSite/adfs/ls' -section:system.webServer/security/authentication/windowsAuthentication /+`"providers.[value='Negotiate']`" /commit:apphost"

Write-Host 'Checking/configuring local registry to support loopback testing...'
$Set = Require-QSRegistryValue -Key 'HKLM:\System\CurrentControlSet\Control\Lsa' -Name 'DisableLoopbackCheck' -PropertyType 'DWord' -Value 1
if (-not $Set) {
Write-Host 'Registry modifications unnecessary.'
} else {
$Values += $script:ADFSSubjectName
Set-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Lsa\MSV1_0' 'BackConnectionHostName' $Values
Write-QSWarning 'Changes made to system requirements require a reboot.'
Write-Host 'Script exiting.'
Exit
}
}

function Configure-QSIISSSL {
Write-Host 'Configuring SSL...'
Require-QSModule WebAdministration
if ($script:ADFSSite -eq $null) {
$script:ADFSSite = Read-QSWebSite
}
if ($script:ADFSSite -eq $null) {
return $false
}
$Certificate = Get-QSADFSCertificate
if ($Certificate -eq $null) {
return $false
}
$BindingOnSite = $false
$SslBindings = @(Get-ChildItem 'IIS:\SslBindings')
if ($SslBindings.Count -ne 0) {
$ExistingBinding = $null
foreach ($SslBinding in $SslBindings) {
foreach ($Site in $SslBinding.Sites) {
if ($Site.Value.Contains($script:ADFSSite)) {
Write-QSWarning 'SSL binding found on existing web site will be removed.'
$ExistingBinding = $SslBinding
}
}
}
if ($ExistingBinding -ne $null) {
Write-Host 'Removing existing binding from the ADFS site...'
Remove-Item -Path $SslBinding.PSPath
}
}
$Sites = Get-ChildItem 'IIS:\Sites'
foreach ($Site in $Sites) {
    $Bindings = $Site.Bindings.Collection
foreach ($Binding in $Bindings) {
$BindingInformation = $Binding.bindingInformation.Split(':')
#$BindingIP = $BindingInformation[0]
$BindingPort = $BindingInformation[1]
#$BindingHostname = $BindingInformation[2]
if ($BindingPort -eq 443) {
$BindingOnSite = $true
}
}
}
if (-not $BindingOnSite) {
New-WebBinding -Name $script:ADFSSite -IP '*' -Port 443 -Protocol 'https'
}
$Certificate | New-Item 'IIS:\SslBindings\0.0.0.0!443'
$true
}

#endregion

#region ----- menu choices -----

function Install-QSSignInAssistantExplicit {
Write-QSTitle 'Install Microsoft Online Services Sign-In Assistant'
$results = Install-QSSignInAssistant
}

function Install-QSMsolServicesModuleExplicit {
Write-QSTitle 'Install Microsoft Online Services Module for Windows PowerShell'
$results = Install-QSMsolServicesModule
}

# Download and run the Office 365 Deployment Readiness Tool
function Launch-QSOffice365DeploymentReadinessTool {
Write-QSTitle 'Download and run the Office 365 Deployment Readiness Tool'
$EXEFilename = $script:CurrentExecutingPath + '\office365deploymentreadinesstool.exe'
$ZipFilename = $script:CurrentExecutingPath + '\office365deploymentreadinesstool.zip'
if (-not (Test-Path $EXEFilename)) {
if (-not (Require-QSDownloadableFile -FileName $ZipFilename -URL 'https://bposast.vo.msecnd.net/O365ReadinessTool.80/office365deploymentreadinesstool.zip')) {
Write-QSError 'Tool download failed.'
return
}
$ShellApplication = New-Object -ComObject 'Shell.Application'
$ZipFile = $ShellApplication.Namespace($ZipFilename)
$Destination = $ShellApplication.Namespace($script:CurrentExecutingPath)
# 0x10 = overwrite, 0x4 = hide copy dialog
$Destination.CopyHere($ZipFile.Items(), 0x14)
Release-QSCOMObject $Destination
Release-QSCOMObject $ZipFile
Release-QSCOMObject $ShellApplication
}
Start-Process -FilePath $EXEFilename
}

function Add-QSMsolDomain {
Write-QSTitle 'Add local UPN suffix as domain in Windows Azure Active Directory'
Require-QSActiveMsolConnection
Write-Host 'Checking for unused UPN suffixes...'
$UpnSuffixes = Get-QSDomainSuffixes
$ActiveDomains = Get-MsolDomain | Foreach-Object { $_.Name }
$UnusedList = @()
foreach ($UpnSuffix in $UpnSuffixes) {
if (-not ($ActiveDomains -contains $UpnSuffix)) {
$UnusedList += $UpnSuffix;
} else {
Write-Host "Found already added domain: $UpnSuffix"
}
}
if ($UnusedList.Count -eq 0) {
Write-Host ' '
Write-Host 'All possible domains have already been added to the service.'
return
}
$SelectedSuffix = Read-QSListChoice -Choices $UnusedList -Prompt 'UPN suffix to add to Windows Azure Active Directory' -Title 'UPN Selection'
if ($SelectedSuffix -eq $null) {
return
}
New-MsolDomain -Name $SelectedSuffix -Authentication Federated
$Domain = Get-MsolDomain -DomainName $SelectedSuffix
if ($Domain.Status -eq 'Verified') {
Write-Host ' '
Write-Host 'Domain is verified. If it is a subdomain of an existing domain, this is automatic.'
Write-Host ' '
} else {
Write-Host ' '
Write-Host -NoNewline 'Domain verification code: '
Get-QSMsolDNSVerificationText -Domain $SelectedSuffix
Write-Host ' '
}
}

# Looks up DNS verification record information
function Get-QSMsolDomainVerificationDnsAll {
Write-QSTitle 'Retrieve verification information for domains in Windows Azure Active Directory'
Require-QSActiveMsolConnection
$UnverifiedDomains = Get-QSUnverifiedDomains
if ($UnverifiedDomains.Count -eq 0) {
Write-Host 'There are no unverified domains in the current tenant.'
return
}
$Results = @();
foreach ($UnverifiedDomain in $UnverifiedDomains) {
$Result = `
New-Object Object | `
Add-Member -PassThru -MemberType 'NoteProperty' -Name 'Domain Name'        -Value $UnverifiedDomain.Name | `
Add-Member -PassThru -MemberType 'NoteProperty' -Name 'Verification Value' -Value ( Get-QSMsolDNSVerificationText -Domain $UnverifiedDomain.Name )
$Results += $Result
}
return $Results
}

# Enables DirSync support
function Set-QSMsolDirSyncEnabled {
Write-QSTitle 'Enable directory synchronization (DirSync) on the tenant'
Require-QSActiveMsolConnection
if ((Get-MSOLCompanyInformation).DirectorySynchronizationEnabled) {
Write-Host 'Directory synchronization support is already enabled for the current tenant.'
return
}
Write-Host 'Requesting directory sync to be enabled. This may take up to 24 hours to complete.'
Set-MsolDirSyncEnabled -EnableDirSync $true
}

# Add ADFS role to this server
function Install-QSADFSRole {
Write-QSTitle 'Add the ADFS role to this server'
Require-QSWindowsFeature ADFS-Federation
}

# Create a service account in the local domain for ADFS use
function New-QSADFSServiceAccount {
Write-QSTitle 'Create a service account in the local domain for ADFS use'
if (-not (Read-QSHostADFSServiceCredentials)) {
return
}
if (($script:ADFSDomainName.ToLower() -ne $env:USERDOMAIN.ToLower()) -and `
($script:ADFSDomainName.ToLower() -ne $env:USERDNSDOMAIN.ToLower())) {
Write-QSError 'The domain for the service account must match the domain of the ADFS server.'
return
}
Require-QSWindowsFeature RSAT-AD-Powershell
Require-QSModule ActiveDirectory
$ExistingUser = $null
try {
$ExistingUser = Get-ADUser $script:ADFSAccountName
}
catch {
}
if ($?) {
Write-QSWarning 'User already exists, skipping creation.'
return
}
Write-Host "Creating user `"$script:ADFSAccountName`"..."
New-ADUser -Name $script:ADFSAccountName `
-SamAccountName $script:ADFSAccountName `
-DisplayName 'ADFS Service Account' `
-AccountPassword $script:ADFSAccountPassword `
-ChangePasswordAtLogon $false `
-PasswordNeverExpires $true `
-Enabled $true
if ($?) {
Write-Host -ForegroundColor 'Green' -BackgroundColor 'Black' 'Creation successful.'
return
} else {
Write-QSError 'Creation failed, please review earlier messages and try again.'
$script:ADFSAccountName = $null
}
}

# Create an internal DNS entry for ADFS
function Add-QSADFSDNSEntry {
Write-QSTitle 'Create an internal DNS entry for ADFS'
$Domain = Read-QSHostDomainChoice
if ($Domain -eq $null) {
return
}
$LocalHostname = $env:COMPUTERNAME.ToLower()
$LocalDNSDomainName = $env:USERDNSDOMAIN.ToLower()
if (($LocalHostname -eq 'adfs') -and ($Domain -eq $LocalDNSDomainName)) {
Write-QSError 'You cannot use a server with the name "ADFS" for hosting ADFS.'
return
}
$ServerAddress = Read-QSHostDNSServerAddress
if ($ServerAddress -eq $null) {
return
}
$IPAddresses = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=TRUE").IPAddress | Select-String -Pattern '^.*\..*\..*\..*$'
$IPAddress = Read-QSListChoice -Choices $IPAddresses -Prompt 'Main ADFS service IP address' -Title 'Local IP Addresses'
if ($IPAddress -eq $null) {
return
}
Require-QSWindowsFeature RSAT-DNS-Server
Require-QSModule DnsServer
Write-Host 'Attempting to add DNS record...'
Add-DnsServerResourceRecordA -ComputerName $ServerAddress -ZoneName $Domain -Name 'adfs' -IPv4Address $IPAddress
if ($?) {
Write-Host 'Complete.'
} else {
Write-QSError 'Record addition failed.'
}
}

# Process SSL certificate for ADFS
function Process-QSCertificate {
Write-QSTitle 'Process SSL certificate for ADFS'
Write-Host 'Checking for existing certificate...'
$Certificate = Get-QSADFSCertificate -SkipVerification -Silent
if ($Certificate -ne $null) {
Write-QSWarning ('Local certificate with friendly name "' + $script:CertificateFriendlyName + '" already exists.')
$ValidateChoice = Read-QSHostYesNo -Title 'Validate Existing?' `
-Prompt 'The certificate already exists. Validate the existing certificate?' `
-YesDefault `
-YesDescription 'Validate the certificate' `
-NoDescription 'Skip validation'
if ($ValidateChoice) {
$Certificate = Get-QSADFSCertificate
if ($Certificate -eq $null) {
Write-QSError 'Validation failed.'
} else {
Write-Host -ForegroundColor 'Green' -BackgroundColor 'Black' 'Validation successful.'
}
} else {
Write-QSWarning 'Validation skipped.'
}
return
}
if (-not (Require-QSADFSSubjectName)) {
return
}
if (-not (Read-QSHostYesNo -Title 'Confirm Self-Signed' `
-Prompt 'Create self-signed certificate?' `
-YesDefault `
-YesDescription 'Create self-signed certificate' `
-NoDescription 'Do not create certificate')) {
Write-QSWarning 'Creation skipped.'
return
}
Write-Host 'Creating private key...'
# subject name
$Name = New-Object -ComObject 'X509Enrollment.CX500DistinguishedName.1' 
$Name.Encode("CN=$script:ADFSSubjectName", 0)
# new key pair
$Key = New-Object -ComObject 'X509Enrollment.CX509PrivateKey.1' 
$Key.ProviderName = 'Microsoft RSA SChannel Cryptographic Provider' 
$Key.KeySpec = 1
$Key.Length = 2048
$Key.SecurityDescriptor = 'D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)' 
$Key.MachineContext = 1
$Key.ExportPolicy = 1
$Key.FriendlyName = $script:CertificateFriendlyName
$Key.Create()
Write-Host 'Creating certificate request details...'
$EnhancedKeyUsageOIDs = New-Object -ComObject 'X509Enrollment.CObjectIds.1' 
$ServerAuthenticationOID = New-Object -ComObject 'X509Enrollment.CObjectId.1' 
$ServerAuthenticationOID.InitializeFromValue('1.3.6.1.5.5.7.3.1')
$EnhancedKeyUsageOIDs.add($ServerAuthenticationOID)
$EnhancedKeyUsageExtension = New-Object -ComObject 'X509Enrollment.CX509ExtensionEnhancedKeyUsage.1' 
$EnhancedKeyUsageExtension.InitializeEncode($EnhancedKeyUsageOIDs)
Write-Host 'Creating certificate request...'
$Certificate = New-Object -ComObject 'X509Enrollment.CX509CertificateRequestCertificate.1' 
# 2 in first parameter = ContextMachine
# '' in third parameter = no template specified
$Certificate.InitializeFromPrivateKey(2, $Key, '')
$Certificate.Subject = $Name 
$Certificate.Issuer = $Certificate.Subject
$Certificate.NotBefore = Get-Date
$Certificate.NotAfter = $Certificate.NotBefore.AddDays(365)
$Certificate.X509Extensions.Add($EnhancedKeyUsageExtension)
if ($script:ADFSSubjectDomainName.ToLower -ne $env:USERDNSDOMAIN) {
$AltNamesCollection = New-Object -ComObject 'X509Enrollment.CAlternativeNames'
    $ExtNames = New-Object -ComObject 'X509Enrollment.CX509ExtensionAlternativeNames'
    $AltDnsName = New-Object -ComObject 'X509Enrollment.CAlternativeName'
    $AltDnsName.InitializeFromString($script:AltNameType.DNS_NAME, ($env:COMPUTERNAME + '.' + $env:USERDNSDOMAIN))
    $AltNamesCollection.Add($AltDnsName)
    $MainDnsName = New-Object -ComObject 'X509Enrollment.CAlternativeName'
    $MainDnsName.InitializeFromString($script:AltNameType.DNS_NAME, $script:ADFSSubjectName)
    $AltNamesCollection.Add($MainDnsName)
    $ExtNames.InitializeEncode($AltNamesCollection)
  $Certificate.X509Extensions.Add($ExtNames)
}
$Certificate.Encode()
Write-Host 'Submitting request...'
$Enrollment = New-Object -ComObject 'X509Enrollment.CX509Enrollment.1' 
$Enrollment.InitializeFromRequest($Certificate)
$Enrollment.CertificateFriendlyName = $Key.FriendlyName
$CertificateData = $Enrollment.CreateRequest(0)
Write-Host 'Installing response...'
# 2 in first parameter = AllowUntrustedCertificate
# 0 in third parameter = XCN_CRYPT_STRING_BASE64HEADER
# '' in fourth parameter = no certificate password
$Enrollment.InstallResponse(2, $CertificateData, 0, '')
# cleanup COM objects
if ($AltNamesCollection -ne $null) {
    Release-QSCOMObject $MainDnsName; $MainDnsName = $null
    Release-QSCOMObject $AltDnsName; $AltDnsName = $null
    Release-QSCOMObject $ExtNames; $ExtNames = $null
Release-QSCOMObject $AltNamesCollection; $AltNamesCollection = $null
}
Release-QSCOMObject $Enrollment; $Enrollment = $null
Release-QSCOMObject $Certificate; $Certificate = $null
Release-QSCOMObject $EnhancedKeyUsageExtension; $EnhancedKeyUsageExtension = $null
Release-QSCOMObject $ServerAuthenticationOID; $ServerAuthenticationOID = $null
Release-QSCOMObject $EnhancedKeyUsageOIDs; $EnhancedKeyUsageOIDs = $null
Release-QSCOMObject $Key; $Key = $null
Release-QSCOMObject $Name; $Name = $null
# Trust the certificate
$Certificate = Get-QSADFSCertificate -SkipVerification
Write-Host 'Importing as trusted root...'
$Store = Get-Item 'cert:\LocalMachine\Root'
$Store.Open('ReadWrite')
$Store.Add($Certificate)
$Store.Close()
Write-Host 'Importing as enterprise trust...'
$Store = Get-Item 'cert:\LocalMachine\Trust'
$Store.Open('ReadWrite')
$Store.Add($Certificate)
$Store.Close()
Write-Host 'Importing as trusted third-party root...'
$Store = Get-Item 'cert:\LocalMachine\AuthRoot'
$Store.Open('ReadWrite')
$Store.Add($Certificate)
$Store.Close()
Write-Host 'Complete.'
}

# Export SSL certificate with private key
function Export-QSCertificate {
Write-QSTitle 'Export SSL certificate with private key'
Write-Host 'Exporting...'
$FinalCertificate = Get-QSADFSCertificate
if ($FinalCertificate -eq $null) {
Write-Error 'Cannot find the self-signed certificate; export failed.'
return
}
$CERFilename = $Script:CertificateFileName.Replace('.pfx', '.cer')
[System.IO.File]::WriteAllBytes($CERFilename, $FinalCertificate.Export('CER'))
[System.IO.File]::WriteAllBytes($script:CertificateFileName, $FinalCertificate.Export('PFX', 'secret'))
Write-Host 'Complete.'
}

# Configure ADFS with basic configuration
function Configure-QSADFS {
Write-QSTitle 'Configure ADFS with basic configuration'
Require-QSWindowsFeature ADFS-Federation
if (-not (Require-QSADFSSubjectName)) {
return
}
if (-not (Read-QSHostADFSServiceCredentials)) {
return
}
$Certificate = Get-QSADFSCertificate
if ($Certificate -eq $null) {
Write-QSError 'No certificate found to use for the installation.'
return
}
if (-not (Configure-QSIISSSL)) {
return
}
#Write-Host 'Stopping Windows Internal Database (if started)...'
#Stop-Service -Name 'Windows Internal Database'
#Write-Host 'Deleting old ADFS databases (if present)...'
#Remove-Item "$env:SystemRoot\WID\Data\Adfs*.*" -ErrorAction 'SilentlyContinue'
Write-Host "Configuring ADFS to run as $script:ADFSDomainName\$script:ADFSAccountName`n" `
' with certificate thumbprint ' $Certificate.Thumbprint '...'
Install-AdfsFarm -CertificateThumbprint $Certificate.Thumbprint `
-FederationServiceName $script:ADFSSubjectName `
-ServiceAccountCredential $script:ADFSCredentials `
-OverwriteConfiguration

if ($?) {
Configure-QSIISAuthentication
}
}

# Confirm/configure Windows Firewall for port 443
function Configure-QSWindowsFirewall {
Write-QSTitle 'Confirm/configure Windows Firewall for port 443'
Require-QSModule NetSecurity
$Rules = Get-NetFirewallPortFilter | Where-Object { ($_.LocalPort -eq 443) -and ($_.Protocol -eq 'TCP') } `
| Get-NetFirewallRule `
| Where-Object { ($_.Direction -eq 'Inbound') -and $_.Enabled -and ($_.Profile -eq 'Any') } `
| Get-NetFirewallAddressFilter | Where-Object { $_.RemoteAddress -eq 'Any' } `
| Get-NetFirewallRule `
| Get-NetFirewallApplicationFilter | Where-Object { @('any', 'system').Contains($_.Program.ToLower()) } `
| Get-NetFirewallRule `
| Get-NetFirewallInterfaceFilter | Where-Object { $_.InterfaceAlias -eq 'Any' } `
| Get-NetFirewallRule `
| Get-NetFirewallInterfaceTypeFilter | Where-Object { $_.InterfaceType -eq 'Any' } `
| Get-NetFirewallRule
if (-not $?) {
Write-QSWarning 'Unable to get firewall rules - Windows Firewall disabled? You must configure any local firewall manually.'
return
}
if ($Rules.Count -eq 0) {
Write-Host 'Adding new SSL incoming rule (TCP port 443).'
New-NetFirewallRule -DisplayName 'ADFS SSL Incoming [TCP 443]' -Direction Inbound -Action Allow -EdgeTraversalPolicy Allow -Protocol TCP -LocalPort 443
} else {
Write-Host 'Windows Firewall appears open for TCP port 443, no changes made.'
}
}

# Launch test web pages
function Launch-QSIETestPages {
Write-QSTitle 'Launch test web pages'
if (-not (Require-QSADFSSubjectName)) {
return
}
Write-Host 'Page launch will take about 10 seconds...'
$JunkResults = [Diagnostics.Process]::Start("$env:SystemRoot\system32\ipconfig.exe", '/flushdns')
Start-Sleep -Seconds 3
$JunkResults = [Diagnostics.Process]::Start("https://$script:ADFSSubjectName/adfs/services/trust/mex")
Start-Sleep -Seconds 3
$JunkResults = [Diagnostics.Process]::Start("https://$script:ADFSSubjectName/FederationMetadata/2007-06/FederationMetadata.xml")
Start-Sleep -Seconds 3
$JunkResults = [Diagnostics.Process]::Start("https://$script:ADFSSubjectName/adfs/ls/IdpInitiatedSignon.aspx")
}

# Import certificates for ADFS Proxy
function Import-QSCertificates {
Write-QSTitle 'Import certificates for ADFS Proxy'
if (-not (Require-QSLocalFile $script:CertificateFileName)) {
return
}
Require-QSModule PKI
$CertificatePassword = ConvertTo-SecureString -String 'secret' -Force -AsPlainText
Write-Host 'Importing as enterprise trust...'
$Results = Import-PfxCertificate -FilePath $script:CertificateFileName -CertStoreLocation 'cert:\LocalMachine\Trust' -Exportable -Password $CertificatePassword
Write-Host 'Importing as trusted root...'
$Results = Import-PfxCertificate -FilePath $script:CertificateFileName -CertStoreLocation 'cert:\LocalMachine\Root' -Exportable -Password $CertificatePassword
Write-Host 'Importing to certificate store...'
$Results = Import-PfxCertificate -FilePath $script:CertificateFileName -CertStoreLocation 'cert:\LocalMachine\My' -Exportable -Password $CertificatePassword
Write-Host 'Complete.'
}

# Add the ADFS Proxy role to this server
function Install-QSADFSProxyRole {
Write-QSTitle 'Add the ADFS Proxy role to this server'
Require-QSWindowsFeature ADFS-Proxy
}

# Configure IIS SSL and authentication
function Configure-QSIISSSLExplicit {
Write-QSTitle 'Configure IIS SSL and authentication'
if (-not (Configure-QSIISSSL)) {
return
}
Configure-QSIISAuthentication
}

# Add a HOSTS file entry for ADFS access from the proxy
function Add-HostsEntryForADFS {
Write-QSTitle 'Add a HOSTS file entry for ADFS access from the proxy'
$Domain = Read-QSHostDomainChoice
if ($Domain -eq $null) {
return
}
$IPAddress = Read-Host 'Enter the IP address of the internal ADFS server'
if ($IPAddress -eq '') {
Write-QSWarning 'Cancelled.'
return
}
$NeedToAdd = $true
$HostsPath = "$env:SystemRoot\System32\drivers\etc\HOSTS"
Copy-Item $HostsPath "$HostsPath.backup"
$Hosts = get-content $hostsPath
$Hosts = $Hosts | Foreach {
if ($_ -match "(.*?\d{1,3}.*?adfs\.$Domain*)") {
Write-QSWarning 'Will remove existing entry'
} else {
$_
}
}
$Hosts = $Hosts + "`n$IPAddress adfs.$Domain"
$Hosts | Out-File $HostsPath -Encoding ASCII
}

# Configure ADFS Proxy with basic configuration
function Configure-QSADFSProxyRole {
Write-QSTitle 'Configure ADFS Proxy with basic configuration'
Require-QSWindowsFeature ADFS-Proxy
if (-not (Read-QSHostADFSServiceCredentials)) {
return
}
Write-Host 'Checking for local certificate...'
$Certificate = Get-QSADFSCertificate
if ($Certificate -eq $null) {
return
}
Write-Host 'Checking for ADFS subject name...'
if (-not (Require-QSADFSSubjectName)) {
return
}
Write-Host 'Configuring ADFS Proxy...'
Add-AdfsProxy -FederationServiceName $script:ADFSSubjectName `
-FederationServiceTrustCredential $script:ADFSCredentials
# Pre-Windows Server 2012 command line to configure ADFS
    # Start-Process -FilePath ("$env:SystemRoot\ADFS\FSPConfigWizard.exe") -Wait -ArgumentList @( `
# '/Hostname', $script:ADFSSubjectName, `
# '/Username', $script:ADFSAccountName, `
# '/Password', (ConvertFrom-QSSecureStringToPlaintext -SecureString $script:ADFSAccountPassword) `
#)
Configure-QSIISAuthentication
}

# Looks up TXT DNS records for unverified domains
function Test-QSExternalDNSRecords {
Write-QSTitle 'Check DNS records for TXT entries for unverified domains'
Require-QSActiveMsolConnection
# Level 3: resolver1.level3.net
$ExternalServer = "209.244.0.3"
$NewHost = Read-Host "Enter the IP address for the external DNS server to query`nor hit Enter for the default of $ExternalServer"
if ($NewHost -ne '') {
$ExternalServer = $NewHost
}
$LookupResults = nslookup www.microsoft.com $ExternalServer 2>&1
if ($LookupResults -match 'Request to .* timed-out') {
Write-QSError "Cannot access external DNS server $ExternalServer."
return
}
$UnverifiedDomains = Get-QSUnverifiedDomains
foreach ($UnverifiedDomain in $UnverifiedDomains) {
Write-Host -NoNewline ('Checking for TXT for "' + $UnverifiedDomain.Name + '"... ')
$LookupResults = nslookup -type=TXT $UnverifiedDomain.Name $ExternalServer 2>&1
$Matched = $LookupResults -match '(MS=ms[0-9]*)+'
if ($Matched.Count -eq 0) {
Write-Host -ForegroundColor 'Red' -BackgroundColor 'Black' 'Failure.'
Write-Host 'No records found. Full results:'
Write-Host $LookupResults
} else {
if ($Matched.Count -ne 1) {
Write-Host -ForegroundColor 'Red' -BackgroundColor 'Black' 'Failure.'
Write-Host 'Expected exactly one record, found' $Matched.Count'.'
} else {
Write-Host -ForegroundColor 'Green' -BackgroundColor 'Black' 'Success.'
Write-Host 'Record found: ' $Matched[0]
$Matched[0] -match 'ms[0-9]+' | Out-Null
$Found = $matches[0]
$Expected = Get-QSMsolDNSVerificationText -Domain $UnverifiedDomain.Name
Write-Host -NoNewLine 'Validating record... '
if ($Found -eq $Expected) {
Write-Host -ForegroundColor 'Green' -BackgroundColor 'Black' 'Success.'
Write-Host 'Record located matched expected record.'
} else {
Write-Host -ForegroundColor 'Red' -BackgroundColor 'Black' 'Failure.'
Write-Host "Found $Found but expected $Expected."
}
}
}
}
}

# Configure Windows Azure AD connection to ADFS
function Convert-QSMsolDomain {
Write-QSTitle 'Configure Windows Azure AD connection to ADFS'
Require-QSActiveMsolConnection
$Domain = Read-QSHostDomainChoice
if ($Domain -eq $null) {
return
}
Write-Host 'Configuring the Windows Azure AD connection to ADFS...' 
New-MsolFederatedDomain -DomainName $Domain
if ($?) {
Write-Host 'Finished.'
}
}

# Create sign-in test user
function New-QSTestUser {
Write-QSTitle 'Create sign-in test user'
$Credentials = Read-QSHostCredentials -Purpose 'Test user'
if ($Credentials -eq $null) {
Write-QSWarning 'Cancelled.'
return
}
$AccountName = $Credentials.Account
$FirstName = Read-Host 'First (given) name of new user'
if ($FirstName -eq '') {
Write-QSWarning 'Cancelled.'
return
}
$LastName = Read-Host 'Last (family) name of new user'
if ($LastName -eq '') {
Write-QSWarning 'Cancelled.'
return
}
$UPNDomain = Read-QSHostDomainChoice
if ($UPNDomain -eq $null) {
return
}
Require-QSWindowsFeature RSAT-AD-Powershell
Require-QSModule ActiveDirectory
$LocalUser = $null
try {
$LocalUser = Get-ADUser $AccountName -Properties 'DisplayName'
}
catch {
}
if ($?) {
Write-QSWarning 'Local user already exists, skipping creation.'
} else {
Write-Host "Creating user `"$AccountName`"..."
New-ADUser -Name $AccountName `
-SamAccountName $AccountName `
-DisplayName 'ADFS Test Account' `
-AccountPassword $Credentials.Password `
-ChangePasswordAtLogon $false `
-PasswordNeverExpires $true `
-Enabled $true `
-UserPrincipalName "$AccountName@$UPNDomain" `
-GivenName $FirstName `
-Surname $LastName
if (-not $?) {
Write-QSError 'Windows Azure Active Directory user creation failed, please review earlier messages and try again.'
return
}
$LocalUser = Get-ADUser $AccountName -Properties 'DisplayName'
}
Write-Host 'Creating corresponding Windows Azure Active Directory user...'
Require-QSActiveMsolConnection
$GUID = $LocalUser.ObjectGuid
$Base64 = [System.Convert]::ToBase64String($GUID.ToByteArray())
New-MsolUser -DisplayName $LocalUser.DisplayName `
-ImmutableId $Base64 `
-UserPrincipalName $LocalUser.UserPrincipalName `
-FirstName $FirstName `
-LastName $LastName `
}

# Download, install, and configure the DirSync tool
function Install-QSDirSync {
Write-QSTitle 'Download, install, and configure the DirSync tool'
$DirSyncFilename = $script:CurrentExecutingPath + '\DirSync.exe'
if (-not (Require-QSDownloadableFile -FileName $DirSyncFilename -URL 'http://g.microsoftonline.com/0BX10en/571')) {
Write-QSError 'DirSync download failed.'
return
}
Write-Host 'Running DirSync installer...'
Start-Process -FilePath $DirSyncFilename -ArgumentList @('/quiet') -Wait
$ConfigWizardFilename = $env:ProgramFiles + '\Microsoft Online Directory Sync\ConfigWizard.exe'
if (-not (Test-Path $ConfigWizardFilename)) {
Write-QSError "Installation appears to have failed, try running $DirSyncFilename interactively."
return
}
Write-QSWarning 'You must sign out and sign in again to continue.'
Write-Host 'Script exiting.'
Exit
}

# Configure the DirSync tool
function Configure-QSDirSync {
Write-QSTitle 'Configure the DirSync tool'
Add-PSSnapIn Coexistence-Configuration
Require-QSActiveMsolConnection
Write-Host 'Requesting synchonization credentials...'
$TargetCredentials = Get-Credential -Message 'Permanent Synchronization Credentials'
Write-Host 'Requesting local credentials...'
$SourceCredentials = Get-Credential -Message 'Local Active Directory Administrator'
Write-Host 'Requesting online coexistence configuration information...'
$Configuration = Get-CoexistenceConfiguration -TargetCredentials $script:MsolCredential
Write-Host 'Configuring local coexistence configuration information...'
Set-CoexistenceConfiguration -SourceCredentials $SourceCredentials -TargetCredentials $TargetCredentials
Write-Host 'Requesting an immediate synchronization...'
Start-OnlineCoexistenceSync
}

# Get the latest Directory Synchronization events
function Get-QSEventLogSyncronizationEvents {
Write-QSTitle 'Get the latest Directory Synchronization events'
Get-EventLog -After ((Get-Date).AddMinutes(-30)) -LogName 'Application' -Source 'Directory Synchronization' | Sort-Object -Property TimeGenerated
}

#endregion

#region ----- main code -----

Test-QSRequirement -Requirement (Get-QSElevationStatus) -Message 'You must launch this script as an administrator.'
Test-QSRequirement -Requirement (-not (Test-QSWin32)) -Message 'You must launch this script in a 64-bit PowerShell session.'
Test-QSRequirement -Requirement (Test-QSServerOS) -Message 'You must run this script on a Server OS SKU.'
Test-QSRequirement -Requirement (Test-QSWindows8OrLater) -Message 'You must run this script on Windows Server 2012 or later.'

Disable-QSInternetExplorerESC

while (1) {
Write-QSTitle -DoubleDashedLine -Title 'Active Directory to Windows Azure Active Directory QuickStart Tool'
@"
Select an operation to continue:
 
 0) EXIT
 
 ADFS Server Options (Part 1)
 ----------------------------
 1) Install Microsoft Online Services Sign-In Assistant
 2) Install Microsoft Online Services Module for Windows PowerShell
 3) Download and run the Office 365 Deployment Readiness Tool
 4) Add local UPN suffix as domain in Windows Azure Active Directory
 5) Retrieve verification information for domains in Windows Azure Active Directory
 6) Enable directory synchronization (DirSync) on the tenant
 7) Add the ADFS role to this server
 8) Create a service account in the local domain for ADFS use
 9) Create an internal DNS entry for ADFS
10) Process SSL certificate for ADFS
11) Export SSL certificate with private key
12) Configure ADFS with basic configuration
13) Confirm/configure Windows Firewall for port 443
14) Launch test web pages
 
 ADFS Proxy Options
 ------------------
15) Import certificates for ADFS Proxy
16) Add the ADFS Proxy role to this server
17) Configure IIS SSL and authentication
18) Add a HOSTS file entry for ADFS access from the proxy
19) Configure ADFS Proxy with basic configuration
20) Confirm/configure Windows Firewall for port 443
21) Launch test web pages

 ADFS Server Options (Part 2)
 ----------------------------
22) Check DNS records for TXT entries for unverified domains
23) Configure Windows Azure AD connection to ADFS
24) Create a single sign-on test user
25) Download and install the DirSync tool
26) Configure the DirSync tool
27) Get the latest Directory Synchronization events
 
"@

$Choice = Read-Host 'Enter your selection'

switch ($Choice) {
 0 { exit }
 1 { Install-QSSignInAssistantExplicit; Write-QSCompletionMessage }
 2 { Install-QSMsolServicesModuleExplicit; Write-QSCompletionMessage }
 3 { Launch-QSOffice365DeploymentReadinessTool; Write-QSCompletionMessage }
 4 { Add-QSMsolDomain; Write-QSCompletionMessage }
 5 { Get-QSMsolDomainVerificationDnsAll; Write-QSCompletionMessage }
 6 { Set-QSMsolDirSyncEnabled; Write-QSCompletionMessage }
 7 { Install-QSADFSRole; Write-QSCompletionMessage }
 8 { New-QSADFSServiceAccount; Write-QSCompletionMessage }
 9 { Add-QSADFSDNSEntry; Write-QSCompletionMessage }
10 { Process-QSCertificate; Write-QSCompletionMessage }
11 { Export-QSCertificate; Write-QSCompletionMessage }
12 { Configure-QSADFS; Write-QSCompletionMessage }
13 { Configure-QSWindowsFirewall; Write-QSCompletionMessage }
14 { Launch-QSIETestPages; Write-QSCompletionMessage }
15 { Import-QSCertificates; Write-QSCompletionMessage }
16 { Install-QSADFSProxyRole; Write-QSCompletionMessage }
17 { Configure-QSIISSSLExplicit; Write-QSCompletionMessage }
18 { Add-HostsEntryForADFS; Write-QSCompletionMessage } 
19 { Configure-QSADFSProxyRole; Write-QSCompletionMessage }
20 { Configure-QSWindowsFirewall; Write-QSCompletionMessage }
21 { Launch-QSIETestPages; Write-QSCompletionMessage }
22 { Test-QSExternalDNSRecords; Write-QSCompletionMessage }
23 { Convert-QSMsolDomain; Write-QSCompletionMessage }
24 { New-QSTestUser; Write-QSCompletionMessage }
25 { Install-QSDirSync; Write-QSCompletionMessage }
26 { Configure-QSDirSync; Write-QSCompletionMessage }
27 { Get-QSEventLogSyncronizationEvents; Write-QSCompletionMessage }
}
}

#endregion