Public/New-DomainController.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
<#
    .SYNOPSIS
        This function creates a new Primary Domain Controller on the specified Windows 2012 R2 or Windows 2016 Server.
 
        This function MUST be used remotely (i.e. run it from a Workstation that can use PS Remoting to access the target
        Windows Server that will become the new Domain Controller).
 
    .DESCRIPTION
        See .SYNOPSIS
 
    .NOTES
 
    .PARAMETER DesiredHostName
        This parameter is MANDATORY.
 
        This parameter takes a string that represents the HostName that you would like the target Windows 2016 Server to have.
 
    .PARAMETER NewDomainName
        This parameter is MANDATORY.
 
        This parameter takes a string that represents the name of the new domain you would like to create.
        Example: alpha.lab
 
    .PARAMETER NewDomainAdminCredentials
        This parameter is MANDATORY.
 
        This parameter takes a PSCredential. A new Domain Account will be created using these credentials. This account will be
        added to the following Security Groups on the New Domain:
            - Domain Admins
            - Domain Users
            - Enterprise Admins
            - Group Policy Creator Owners
            - Schema Admins
 
    .PARAMETER LocalAdministratorAccountCredentials
        This parameter is MANDATORY.
 
        This parameter takes a PSCredential.
 
        The credential provided to this parameter will be applied to the Local Built-In Administrator Account on the
        target Windows Server. In other words, the pscredential provided to this parameter does NOT need to match
        the current UserName/Password of the Local Administrator Account on the target Windows Server, because the
        pscredential provided to this parameter will overwrite whatever the existing credentials are.
 
    .PARAMETER PSRemotingLocalAdminCredentials
        This parameter is MANDATORY.
 
        This parameter takes a PSCredential.
 
        The credential provided to this parameter should correspond to a User Account that has permission to
        remote into the target Windows Server. If you're using a Vagrant Box (which is what will be deployed
        if you use the -CreateNewVMs switch), then the value for this parameter should be created via:
 
            $VagrantVMPassword = ConvertTo-SecureString 'vagrant' -AsPlainText -Force
            $VagrantVMAdminCreds = [pscredential]::new("vagrant",$VagrantVMPassword)
 
    .PARAMETER ServerIP
        This parameter is OPTIONAL, however, if you do NOT use the -CreateNewVMs parameter, this parameter becomes MANDATORY.
 
        This parameter takes a string that represents an IPv4 Address of the Windows Server that will become the new Primary
        Domain Controller.
 
    .PARAMETER RemoteDSCDirectory
        This parameter is OPTIONAL, however, the value defaults to "C:\DSCConfigs".
 
        This parameter takes a string that represents the full path to a directory on -ServerIP that will contain the DSC
        configuration files needed to create the new Primary Domain Controller.
 
    .PARAMETER DSCResultsDownloadDirectory
        This parameter is OPTIONAL, however, the value defaults to "$HOME\Downloads\DSCConfigResultsFor$DesiredHostName".
 
        This parameter takes a string that represents the full path to a directory on the localhost that will contain any
        DSC config output files generated by creating the new Primary Domain Controller. This makes it easy to review what
        DSC did on the remote host.
 
    .EXAMPLE
        # Open an elevated PowerShell Session, import the module, and -
 
        PS C:\Users\zeroadmin> $VagrantVMPassword = ConvertTo-SecureString 'vagrant' -AsPlainText -Force
        PS C:\Users\zeroadmin> $VagrantVMAdminCreds = [pscredential]::new("vagrant",$VagrantVMPassword)
        PS C:\Users\zeroadmin> $DomainAdminCreds = [pscredential]::new("alpha\alphaadmin",$(Read-Host 'Enter Passsword' -AsSecureString))
        Enter Passsword: ************
        PS C:\Users\zeroadmin> $LocalAdminAccountCreds = [pscredential]::new("Administrator",$(Read-Host 'Enter Passsword' -AsSecureString))
        Enter Passsword: ****************
        PS C:\Users\zeroadmin> $NewDomainControllerSplatParams = @{
        >> DesiredHostName = "AlphaDC01"
        >> NewDomainName = "alpha.lab"
        >> NewDomainAdminCredentials = $DomainAdminCreds
        >> ServerIP = "192.168.2.112"
        >> PSRemotingLocalAdminCredentials = $VagrantVMAdminCreds
        >> LocalAdministratorAccountCredentials = $LocalAdminAccountCreds
        >> }
        PS C:\Users\zeroadmin> $NewDomainControllerResults = New-DomainController @NewDomainControllerSplatParams
         
#>

function New-DomainController {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$True)]
        [ValidatePattern("^[a-zA-Z0-9]{4,10}$")]
        [string]$DesiredHostName,

        [Parameter(Mandatory=$True)]
        [ValidatePattern("^([a-z0-9]+(-[a-z0-9]+)*\.)+([a-z]){2,}$")]
        [string]$NewDomainName,

        [Parameter(Mandatory=$True)]
        [pscredential]$NewDomainAdminCredentials,

        [Parameter(Mandatory=$True)]
        [pscredential]$LocalAdministratorAccountCredentials,

        [Parameter(Mandatory=$True)]
        [pscredential]$PSRemotingLocalAdminCredentials,

        [Parameter(Mandatory=$True)]
        [string]$ServerIP,

        [Parameter(Mandatory=$False)]
        [string]$RemoteDSCDirectory,

        [Parameter(Mandatory=$False)]
        [string]$DSCResultsDownloadDirectory
    )

    #region >> Prep

    if (!$RemoteDSCDirectory) {
        $RemoteDSCDirectory = "C:\DSCConfigs"
    }
    if (!$DSCResultsDownloadDirectory) {
        $DSCResultsDownloadDirectory = "$HOME\Downloads\DSCConfigResultsFor$DesiredHostName"
    }
    if ($LocalAdministratorAccountCredentials.UserName -ne "Administrator") {
        Write-Error "The -LocalAdministratorAccount PSCredential must have a UserName property equal to 'Administrator'! Halting!"
        $global:FunctionResult = "1"
        return
    }
    $NewDomainShortName = $($NewDomainName -split "\.")[0]
    if ($NewDomainAdminCredentials.UserName -notmatch "$NewDomainShortName\\[\w]+$") {
        Write-Error "The User Account provided to the -NewDomainAdminCredentials parameter must be in format: $NewDomainShortName\\<UserName>`nHalting!"
        $global:FunctionResult = "1"
        return
    }
    if ($NewDomainAdminCredentials.UserName -match "$NewDomainShortName\\Administrator$") {
        Write-Error "The User Account provided to the -NewDomainAdminCredentials cannot be: $NewDomainShortName\\Administrator`nHalting!"
        $global:FunctionResult = "1"
        return
    }

    $PrimaryIfIndex = $(Get-CimInstance Win32_IP4RouteTable | Where-Object {
        $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0'
    } | Sort-Object Metric1)[0].InterfaceIndex
    $NicInfo = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.InterfaceIndex -eq $PrimaryIfIndex}
    $PrimaryIP = $NicInfo.IPAddress | Where-Object {TestIsValidIPAddress -IPAddress $_}
    if ($ServerIP -eq $PrimaryIP) {
        Write-Error "This $($MyInvocation.MyCommand.Name) function must be run remotely (i.e. from a workstation that can access the target Windows Server via PS Remoting)! Halting!"
        $global:FunctionResult = "1"
        return
    }

    $CharacterIndexToSplitOn = [Math]::Round($(0..$($NewDomainAdminCredentials.UserName.Length) | Measure-Object -Average).Average)
    $NewDomainAdminFirstName = $NewDomainAdminCredentials.UserName.SubString(0,$CharacterIndexToSplitOn)
    $NewDomainAdminLastName = $NewDomainAdminCredentials.UserName.SubString($CharacterIndexToSplitOn,$($($NewDomainAdminCredentials.UserName.Length)-$CharacterIndexToSplitOn))

    $NewBackupDomainAdminFirstName = $($NewDomainAdminCredentials.UserName -split "\\")[-1]
    $NewBackupDomainAdminLastName =  "backup"
    
    $NeededDSCResources = @(
        "PSDesiredStateConfiguration"
        "xPSDesiredStateConfiguration"
        "xActiveDirectory"
    )

    [System.Collections.ArrayList]$DSCModulesToTransfer = @()
    foreach ($DSCResource in $NeededDSCResources) {
        # NOTE: Usually $Module.ModuleBase is the version number directory, and its parent is the
        # directory that actually matches the Module Name. $ModuleBaseParent is the name of the
        # directory that matches the name of the Module
        $ModMapObj = $script:ModuleDependenciesMap.SuccessfulModuleImports | Where-Object {$_.ModuleName -eq $DSCResource}
        #$ModMapObj = GetModMapObject -PotentialModMapObject $PotentialModMapObject

        $ModuleBaseParent = $($ModMapObj.ManifestFileItem.FullName -split $DSCResource)[0] + $DSCResource
        
        if ($DSCResource -ne "PSDesiredStateConfiguration") {
            $null = $DSCModulesToTransfer.Add($ModuleBaseParent)
        }

        switch ($DSCResource) {
            'PSDesiredStateConfiguration' {
                try {
                    $PSDSCVersionPrep = $ModMapObj.ManifestFileItem.FullName
                    if ($PSDSCVersionPrep) {
                        $PSDSCVersion = $PSDSCVersionPrep | Split-Path -Parent | Split-Path -Leaf
                    }
                    else {
                        throw
                    }
                }
                catch {
                    try {
                        $PSDSCModule = Get-Module -ListAvailable "PSDesiredStateConfiguration"
                        $PSDSCVersion = $($PSDSCModule.Version | Sort-Object | Get-Unique).ToString()
                    }
                    catch {
                        Write-Verbose "Unable to get PSDesiredStateConfiguration version information from $env:ComputerName"
                    }
                }
            }
        
            'xPSDesiredStateConfiguration' {
                $xPSDSCVersion = $ModMapObj.ManifestFileItem.FullName | Split-Path -Parent | Split-Path -Leaf
            }
        
            'xActiveDirectory' {
                $xActiveDirectoryVersion = $ModMapObj.ManifestFileItem.FullName | Split-Path -Parent | Split-Path -Leaf
            }
        }
    }

    # Make sure WinRM in Enabled and Running on $env:ComputerName
    try {
        $null = Enable-PSRemoting -Force -ErrorAction Stop
    }
    catch {
        $NICsWPublicProfile = @(Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -eq 0})
        if ($NICsWPublicProfile.Count -gt 0) {
            foreach ($Nic in $NICsWPublicProfile) {
                Set-NetConnectionProfile -InterfaceIndex $Nic.InterfaceIndex -NetworkCategory 'Private'
            }
        }

        try {
            $null = Enable-PSRemoting -Force
        }
        catch {
            Write-Error $_
            Write-Error "Problem with Enabble-PSRemoting WinRM Quick Config! Halting!"
            $global:FunctionResult = "1"
            return
        }
    }

    # If $env:ComputerName is not part of a Domain, we need to add this registry entry to make sure WinRM works as expected
    if (!$(Get-CimInstance Win32_Computersystem).PartOfDomain) {
        $null = reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
    }

    # Add the New Server's IP Addresses to $env:ComputerName's TrustedHosts
    $CurrentTrustedHosts = $(Get-Item WSMan:\localhost\Client\TrustedHosts).Value
    [System.Collections.ArrayList][array]$CurrentTrustedHostsAsArray = $CurrentTrustedHosts -split ','

    $IPsToAddToWSMANTrustedHosts = @($ServerIP)
    foreach ($IPAddr in $IPsToAddToWSMANTrustedHosts) {
        if ($CurrentTrustedHostsAsArray -notcontains $IPAddr) {
            $null = $CurrentTrustedHostsAsArray.Add($IPAddr)
        }
    }
    $UpdatedTrustedHostsString = $($CurrentTrustedHostsAsArray | Where-Object {![string]::IsNullOrWhiteSpace($_)}) -join ','
    Set-Item WSMan:\localhost\Client\TrustedHosts $UpdatedTrustedHostsString -Force

    #endregion >> Prep


    #region >> Helper Functions

    # New-SelfSignedCertifciateEx
    # Get-DSCEncryptionCert
    
    #endregion >> Helper Functions

    
    #region >> Rename Computer

    # Waiting for maximum of 15 minutes for the Server to accept new PSSessions...
    $Counter = 0
    while (![bool]$(Get-PSSession -Name "To$DesiredHostName" -ErrorAction SilentlyContinue)) {
        try {
            New-PSSession -ComputerName $ServerIP -Credential $PSRemotingLocalAdminCredentials -Name "To$DesiredHostName" -ErrorAction SilentlyContinue
            if (![bool]$(Get-PSSession -Name "To$DesiredHostName" -ErrorAction SilentlyContinue)) {throw}
        }
        catch {
            if ($Counter -le 60) {
                Write-Warning "New-PSSession 'To$DesiredHostName' failed. Trying again in 15 seconds..."
                Start-Sleep -Seconds 15
            }
            else {
                Write-Error "Unable to create new PSSession to 'To$DesiredHostName' using Local Admin account '$($PSRemotingLocalAdminCredentials.UserName)'! Halting!"
                $global:FunctionResult = "1"
                return
            }
        }
        $Counter++
    }

    $InvCmdCheckSB = {
        # Make sure the Local 'Administrator' account has its password set
        $UserAccount = Get-LocalUser -Name "Administrator"
        $UserAccount | Set-LocalUser -Password $args[0]
        $env:ComputerName
    }
    $InvCmdCheckSplatParams = @{
        Session                 = Get-PSSession -Name "To$DesiredHostName"
        ScriptBlock             = $InvCmdCheckSB
        ArgumentList            = $LocalAdministratorAccountCredentials.Password
        ErrorAction             = "Stop"
    }
    try {
        $RemoteHostName = Invoke-Command @InvCmdCheckSplatParams
    }
    catch {
        Write-Error $_
        $global:FunctionResult = "1"
        return
    }

    if ($RemoteHostName -ne $DesiredHostName) {
        $RenameComputerSB = {
            Rename-Computer -NewName $args[0] -LocalCredential $args[1] -Force -Restart -ErrorAction SilentlyContinue
        }
        $InvCmdRenameComputerSplatParams = @{
            Session         = Get-PSSession -Name "To$DesiredHostName"
            ScriptBlock     = $RenameComputerSB
            ArgumentList    = $DesiredHostName,$PSRemotingLocalAdminCredentials
            ErrorAction     = "SilentlyContinue"
        }
        try {
            Invoke-Command @InvCmdRenameComputerSplatParams
        }
        catch {
            Write-Error "Problem with renaming the $ServerIP to $DesiredHostName! Halting!"
            $global:FunctionResult = "1"
            return
        }

        Write-Host "Sleeping for 5 minutes to give the Server a chance to restart after name change..."
        Start-Sleep -Seconds 300
    }

    #endregion >> Rename Computer


    #region >> Wait For HostName Change

    Get-PSSession -Name "To$DesiredHostName" | Remove-PSSession
    
    # Waiting for maximum of 15 minutes for the Server to accept new PSSessions Post Name Change Reboot...
    $Counter = 0
    while (![bool]$(Get-PSSession -Name "To$DesiredHostName" -ErrorAction SilentlyContinue)) {
        try {
            New-PSSession -ComputerName $ServerIP -Credential $PSRemotingLocalAdminCredentials -Name "To$DesiredHostName" -ErrorAction SilentlyContinue
            if (![bool]$(Get-PSSession -Name "To$DesiredHostName" -ErrorAction SilentlyContinue)) {throw}
        }
        catch {
            if ($Counter -le 60) {
                Write-Warning "New-PSSession 'To$DesiredHostName' failed. Trying again in 15 seconds..."
                Start-Sleep -Seconds 15
            }
            else {
                Write-Error "Unable to create new PSSession to 'To$DesiredHostName' using Local Admin account '$($PSRemotingLocalAdminCredentials.UserName)'! Halting!"
                $global:FunctionResult = "1"
                return
            }
        }
        $Counter++
    }

    #endregion >> Wait for HostName Change

    
    #region >> Prep DSC On the RemoteHost

    try {
        # Copy the DSC PowerShell Modules to the Remote Host
        $ProgramFilesPSModulePath = "C:\Program Files\WindowsPowerShell\Modules"
        foreach ($ModuleDirPath in $DSCModulesToTransfer) {
            $CopyItemSplatParams = @{
                Path            = $ModuleDirPath
                Recurse         = $True
                Destination     = "$ProgramFilesPSModulePath\$($ModuleDirPath | Split-Path -Leaf)"
                ToSession       = Get-PSSession -Name "To$DesiredHostName"
                Force           = $True
            }
            Copy-Item @CopyItemSplatParams
        }

        $FunctionsForRemoteUse = @(
            ${Function:Get-DSCEncryptionCert}.Ast.Extent.Text
            ${Function:New-SelfSignedCertificateEx}.Ast.Extent.Text
        )

        $DSCPrepSB = {
            # Load the functions we packed up:
            $using:FunctionsForRemoteUse | foreach { Invoke-Expression $_ }

            if (!$(Test-Path $using:RemoteDSCDirectory)) {
                $null = New-Item -ItemType Directory -Path $using:RemoteDSCDirectory -Force
            }

            if ($($env:PSModulePath -split ";") -notcontains $using:ProgramFilesPSModulePath) {
                $env:PSModulePath = $using:ProgramFilesPSModulePath + ";" + $env:PSModulePath
            }

            # Setup WinRM
            try {
                $null = Enable-PSRemoting -Force -ErrorAction Stop
            }
            catch {
                $NICsWPublicProfile = @(Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -eq 0})
                if ($NICsWPublicProfile.Count -gt 0) {
                    foreach ($Nic in $NICsWPublicProfile) {
                        Set-NetConnectionProfile -InterfaceIndex $Nic.InterfaceIndex -NetworkCategory 'Private'
                    }
                }
            
                try {
                    $null = Enable-PSRemoting -Force
                }
                catch {
                    Write-Error $_
                    Write-Error "Problem with Enable-PSRemoting WinRM Quick Config! Halting!"
                    $global:FunctionResult = "1"
                    return
                }
            }
            
            # If $env:ComputerName is not part of a Domain, we need to add this registry entry to make sure WinRM works as expected
            if (!$(Get-CimInstance Win32_Computersystem).PartOfDomain) {
                $null = reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
            }

            $DSCEncryptionCACertInfo = Get-DSCEncryptionCert -MachineName $using:DesiredHostName -ExportDirectory $using:RemoteDSCDirectory

            #### Configure the Local Configuration Manager (LCM) ####
            if (Test-Path "$using:RemoteDSCDirectory\$using:DesiredHostName.meta.mof") {
                Remove-Item "$using:RemoteDSCDirectory\$using:DesiredHostName.meta.mof" -Force
            }
            Configuration LCMConfig {
                Node "localhost" {
                    LocalConfigurationManager {
                        ConfigurationMode = "ApplyAndAutoCorrect"
                        RefreshFrequencyMins = 30
                        ConfigurationModeFrequencyMins = 15
                        RefreshMode = "PUSH"
                        RebootNodeIfNeeded = $True
                        ActionAfterReboot = "ContinueConfiguration"
                        CertificateId = $DSCEncryptionCACertInfo.CertInfo.Thumbprint
                    }
                }
            }
            # Create the .meta.mof file
            $LCMMetaMOFFileItem = LCMConfig -OutputPath $using:RemoteDSCDirectory
            if (!$LCMMetaMOFFileItem) {
                Write-Error "Problem creating the .meta.mof file for $using:DesiredHostName!"
                return
            }
            # Make sure the .mof file is directly under $usingRemoteDSCDirectory alongside the encryption Cert
            if ($LCMMetaMOFFileItem.FullName -ne "$using:RemoteDSCDirectory\$($LCMMetaMOFFileItem.Name)") {
                Copy-Item -Path $LCMMetaMOFFileItem.FullName -Destination "$using:RemoteDSCDirectory\$($LCMMetaMOFFileItem.Name)" -Force
            }

            # Apply the .meta.mof (i.e. LCM Settings)
            Write-Host "Applying LCM Config..."
            $null = Set-DscLocalConfigurationManager -Path $using:RemoteDSCDirectory -Force

            # Output the DSC Encryption Certificate Info
            $DSCEncryptionCACertInfo
        }

        $DSCEncryptionCACertInfo = Invoke-Command -Session $(Get-PSSession -Name "To$DesiredHostName") -ScriptBlock $DSCPrepSB

        if (!$(Test-Path $DSCResultsDownloadDirectory)) {
            $null = New-Item -ItemType Directory -Path $DSCResultsDownloadDirectory
        }
        $CopyItemSplatParams = @{
            Path            = "$RemoteDSCDirectory\DSCEncryption.cer"
            Recurse         = $True
            Destination     = "$DSCResultsDownloadDirectory\DSCEncryption.cer"
            FromSession       = Get-PSSession -Name "To$DesiredHostName"
            Force           = $True   
        }
        Copy-Item @CopyItemSplatParams
    }
    catch {
        Write-Error $_
        $global:FunctionResult = "1"
        return
    }

    #endregion >> Prep DSC On the RemoteHost


    #region >> Apply DomainController DSC Config

    # The below commented config info is loaded in the Invoke-Command ScriptBlock, but is also commented out here
    # so that it's easier to review $StandaloneRootCAConfigAsStringPrep
    <#
    $ConfigData = @{
        AllNodes = @(
            @{
 
                NodeName = '*'
                PsDscAllowDomainUser = $true
                PsDscAllowPlainTextPassword = $true
            }
            @{
                NodeName = $DesiredHostName
                Purpose = 'Domain Controller'
                WindowsFeatures = 'AD-Domain-Services','RSAT-AD-Tools'
                RetryCount = 20
                RetryIntervalSec = 30
            }
        )
 
        NonNodeData = @{
            DomainName = $NewDomainName
            ADGroups = 'Information Systems'
            OrganizationalUnits = 'Information Systems','Executive'
            AdUsers = @(
                @{
                    FirstName = $NewBackupDomainAdminFirstName
                    LastName = $NewBackupDomainAdminLastName
                    Department = 'Information Systems'
                    Title = 'System Administrator'
                }
            )
        }
    }
    #>


    $NewDomainControllerConfigAsStringPrep = @(
        'configuration NewDomainController {'
        ' param ('
        ' [Parameter(Mandatory=$True)]'
        ' [pscredential]$NewDomainAdminCredentials,'
        ''
        ' [Parameter(Mandatory=$True)]'
        ' [pscredential]$LocalAdministratorAccountCredentials'
        ' )'
        ''
        " #Import-DscResource -ModuleName 'PSDesiredStateConfiguration' -ModuleVersion $PSDSCVersion"
        " Import-DscResource -ModuleName 'xPSDesiredStateConfiguration' -ModuleVersion $xPSDSCVersion"
        " Import-DscResource -ModuleName 'xActiveDirectory' -ModuleVersion $xActiveDirectoryVersion"
        ''
        ' $NewDomainAdminUser = $($NewDomainAdminCredentials.UserName -split "\\")[-1]'
        ' $NewDomainAdminUserBackup = $NewDomainAdminUser + "backup"'
        ' '
        ' Node $AllNodes.where({ $_.Purpose -eq "Domain Controller" }).NodeName'
        ' {'
        ' @($ConfigurationData.NonNodeData.ADGroups).foreach({'
        ' xADGroup $_'
        ' {'
        ' Ensure = "Present"'
        ' GroupName = $_'
        ' DependsOn = "[xADUser]FirstUser"'
        ' }'
        ' })'
        ''
        ' @($ConfigurationData.NonNodeData.OrganizationalUnits).foreach({'
        ' xADOrganizationalUnit $_'
        ' {'
        ' Ensure = "Present"'
        ' Name = ($_ -replace "-")'
        ' Path = ("DC={0},DC={1}" -f ($ConfigurationData.NonNodeData.DomainName -split "\.")[0], ($ConfigurationData.NonNodeData.DomainName -split "\.")[1])'
        ' DependsOn = "[xADUser]FirstUser"'
        ' }'
        ' })'
        ''
        ' @($ConfigurationData.NonNodeData.ADUsers).foreach({'
        ' xADUser "$($_.FirstName) $($_.LastName)"'
        ' {'
        ' Ensure = "Present"'
        ' DomainName = $ConfigurationData.NonNodeData.DomainName'
        ' GivenName = $_.FirstName'
        ' SurName = $_.LastName'
        ' UserName = ("{0}{1}" -f $_.FirstName, $_.LastName)'
        ' Department = $_.Department'
        ' Path = ("OU={0},DC={1},DC={2}" -f $_.Department, ($ConfigurationData.NonNodeData.DomainName -split "\.")[0], ($ConfigurationData.NonNodeData.DomainName -split "\.")[1])'
        ' JobTitle = $_.Title'
        ' Password = $NewDomainAdminCredentials'
        ' DependsOn = "[xADOrganizationalUnit]$($_.Department)"'
        ' }'
        ' })'
        ''
        ' ($Node.WindowsFeatures).foreach({'
        ' WindowsFeature $_'
        ' {'
        ' Ensure = "Present"'
        ' Name = $_'
        ' }'
        ' })'
        ''
        ' xADDomain ADDomain'
        ' {'
        ' DomainName = $ConfigurationData.NonNodeData.DomainName'
        ' DomainAdministratorCredential = $LocalAdministratorAccountCredentials'
        ' SafemodeAdministratorPassword = $LocalAdministratorAccountCredentials'
        ' DependsOn = "[WindowsFeature]AD-Domain-Services"'
        ' }'
        ''
        ' xWaitForADDomain DscForestWait'
        ' {'
        ' DomainName = $ConfigurationData.NonNodeData.DomainName'
        ' DomainUserCredential = $LocalAdministratorAccountCredentials'
        ' RetryCount = $Node.RetryCount'
        ' RetryIntervalSec = $Node.RetryIntervalSec'
        ' DependsOn = "[xADDomain]ADDomain"'
        ' }'
        ''
        ' xADUser FirstUser'
        ' {'
        ' DomainName = $ConfigurationData.NonNodeData.DomainName'
        ' DomainAdministratorCredential = $LocalAdministratorAccountCredentials'
        ' UserName = $NewDomainAdminUser'
        ' Password = $NewDomainAdminCredentials'
        ' Ensure = "Present"'
        ' DependsOn = "[xWaitForADDomain]DscForestWait"'
        ' }'
        ''
        ' xADGroup DomainAdmins {'
        ' GroupName = "Domain Admins"'
        ' MembersToInclude = $NewDomainAdminUser,$NewDomainAdminUserBackup'
        ' DependsOn = "[xADUser]FirstUser"'
        ' }'
        ' '
        ' xADGroup EnterpriseAdmins {'
        ' GroupName = "Enterprise Admins"'
        ' GroupScope = "Universal"'
        ' MembersToInclude = $NewDomainAdminUser,$NewDomainAdminUserBackup'
        ' DependsOn = "[xADUser]FirstUser"'
        ' }'
        ''
        ' xADGroup GroupPolicyOwners {'
        ' GroupName = "Group Policy Creator Owners"'
        ' MembersToInclude = $NewDomainAdminUser,$NewDomainAdminUserBackup'
        ' DependsOn = "[xADUser]FirstUser"'
        ' }'
        ''
        ' xADGroup SchemaAdmins {'
        ' GroupName = "Schema Admins"'
        ' GroupScope = "Universal"'
        ' MembersToInclude = $NewDomainAdminUser,$NewDomainAdminUserBackup'
        ' DependsOn = "[xADUser]FirstUser"'
        ' }'
        ' }'
        '}'
    )

    try {
        $NewDomainControllerConfigAsString = [scriptblock]::Create($($NewDomainControllerConfigAsStringPrep -join "`n")).ToString()
    }
    catch {
        Write-Error $_
        Write-Error "There is a problem with the NewDomainController DSC Configuration Function! Halting!"
        $global:FunctionResult = "1"
        return
    }

    $NewDomainControllerSB = {
        #### Apply the DSC Configuration ####
        # Load the NewDomainController DSC Configuration function
        $using:NewDomainControllerConfigAsString | Invoke-Expression

        $NewDomainControllerConfigData = @{
            AllNodes = @(
                @{
                    NodeName = '*'
                    PsDscAllowDomainUser = $true
                    #PsDscAllowPlainTextPassword = $true
                    CertificateFile = $using:DSCEncryptionCACertInfo.CertFile.FullName
                    Thumbprint = $using:DSCEncryptionCACertInfo.CertInfo.Thumbprint
                }
                @{
                    NodeName = $using:DesiredHostName
                    Purpose = 'Domain Controller'
                    WindowsFeatures = 'AD-Domain-Services','RSAT-AD-Tools'
                    RetryCount = 20
                    RetryIntervalSec = 30
                }
            )
    
            NonNodeData = @{
                DomainName = $using:NewDomainName
                ADGroups = 'Information Systems'
                OrganizationalUnits = 'Information Systems','Executive'
                AdUsers = @(
                    @{
                        FirstName = $using:NewBackupDomainAdminFirstName
                        LastName = $using:NewBackupDomainAdminLastName
                        Department = 'Information Systems'
                        Title = 'System Administrator'
                    }
                )
            }
        }

        # IMPORTANT NOTE: The resulting .mof file (representing the DSC configuration), will be in the
        # directory "$using:RemoteDSCDir\STANDALONE_ROOTCA"
        if (Test-Path "$using:RemoteDSCDirectory\$($using:DesiredHostName).mof") {
            Remove-Item "$using:RemoteDSCDirectory\$($using:DesiredHostName).mof" -Force
        }
        $NewDomainControllerConfigSplatParams = @{
            NewDomainAdminCredentials               = $using:NewDomainAdminCredentials
            LocalAdministratorAccountCredentials    = $using:LocalAdministratorAccountCredentials
            OutputPath                              = $using:RemoteDSCDirectory
            ConfigurationData                       = $NewDomainControllerConfigData
        }
        $MOFFileItem = NewDomainController @NewDomainControllerConfigSplatParams
        if (!$MOFFileItem) {
            Write-Error "Problem creating the .mof file for $using:DesiredHostName!"
            return
        }

        # Make sure the .mof file is directly under $usingRemoteDSCDirectory alongside the encryption Cert
        if ($MOFFileItem.FullName -ne "$using:RemoteDSCDirectory\$($MOFFileItem.Name)") {
            Copy-Item -Path $MOFFileItem.FullName -Destination "$using:RemoteDSCDirectory\$($MOFFileItem.Name)" -Force
        }

        # Apply the .mof (i.e. setup the New Domain Controller)
        Write-Host "Applying NewDomainController Config..."
        Start-DscConfiguration -Path $using:RemoteDSCDirectory -Force -Wait
    }
    
    try {
        $NewDCDSCApplication = Invoke-Command -Session $(Get-PSSession -Name "To$DesiredHostName") -ScriptBlock $NewDomainControllerSB
    }
    catch {
        Write-Error $_
        $global:FunctionResult = "1"
        return
    }

    Write-Host "Sleeping for 5 minutes to give the new Domain Controller a chance to finish implementing config..."
    Start-Sleep -Seconds 300

    # Try to use $NewDomainAdminCredentials to create a PSSession with the Domain Controller
    # Try for maximum of 15 minutes and then give up
    $Counter = 0
    while (![bool]$(Get-PSSession -Name "ToDCPostDomainCreation" -ErrorAction SilentlyContinue)) {
        try {
            New-PSSession -ComputerName $ServerIP -Credential $NewDomainAdminCredentials -Name "ToDCPostDomainCreation" -ErrorAction SilentlyContinue
            if (![bool]$(Get-PSSession -Name "ToDCPostDomainCreation" -ErrorAction SilentlyContinue)) {throw}
        }
        catch {
            if ($Counter -le 60) {
                Write-Warning "New-PSSession 'ToDCPostDomainCreation' failed. Trying again in 15 seconds..."
                Start-Sleep -Seconds 15
            }
            else {
                Write-Error "Unable to create new PSSession to 'ToDCPostDomainCreation' using New Domain Admin account '$($NewDomainAdminCredentials.UserName)'! Halting!"
                $global:FunctionResult = "1"
                return
            }
        }
        $Counter++
    }

    if ([bool]$(Get-PSSession -Name "ToDCPostDomainCreation" -ErrorAction SilentlyContinue)) {
        # Make sure we have a Primary Reverse lookup zone
        $ThisModuleFunctionsStringArray = $(Get-Module MiniLab).Invoke({$FunctionsForSBUse})

        try {
            $AddReverseLookupZoneResult = Invoke-Command -Session $(Get-PSSession -Name "ToDCPostDomainCreation") -ScriptBlock {
                $using:ThisModuleFunctionsStringArray | Where-Object {$_ -ne $null} | foreach {Invoke-Expression $_ -ErrorAction SilentlyContinue}    

                $PrimaryIfIndex = $(Get-CimInstance Win32_IP4RouteTable | Where-Object {
                    $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0'
                } | Sort-Object Metric1)[0].InterfaceIndex
                $NicInfo = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.InterfaceIndex -eq $PrimaryIfIndex}
                $PrimaryIP = $NicInfo.IPAddress | Where-Object {TestIsValidIPAddress -IPAddress $_}
                $Prefix = $(Get-NetIPAddress -IPAddress $PrimaryIP).PrefixLength

                $ip = [ipaddress]$PrimaryIP
                $MaskString = $(ConvertSubnetMask -CIDR $Prefix).Mask
                $mask = [ipaddress]$MaskString
                $netid = ([ipaddress]($ip.Address -band $mask.Address)).IPAddressToString
                $binary = [convert]::ToString($mask.Address, 2)
                $mask_length = ($binary -replace 0,$null).Length
                $NetworkAndSubnetMaskCidr = '{0}/{1}' -f $netid, $mask_length
                $NetIdOctetArray = $netid -split '\.'
                $ZoneNameCheck = $NetIdOctetArray[2] + '.' + $NetIdOctetArray[1] + '.' + $NetIdOctetArray[0] + '.' + 'in-addr.arpa'

                if ($(Get-DnsServerZone).ZoneName -notcontains $ZoneNameCheck) {
                    Add-DnsServerPrimaryZone -DynamicUpdate Secure -NetworkId $NetworkAndSubnetMaskCidr -ReplicationScope Domain
                }
            }
        }
        catch {
            Write-Warning "Problem adding Primary Reverse Lookup Zone"
        }

        "DC Installation Success"
    }
    else {
        "DC Installation Failure"
    }

    #endregion >> Apply DomainController DSC Config
}