Wednesday, January 7, 2015

PowerShell one liner script to dcpromo using an IFM backup

Did you ever just want to log in to a server and run a single script to promote the server to a domain controller using an IFM backup, and get it all done in only one step?

First, what to know about this script.
I believe that PowerShell version 3 is the lowest that this can be run in, and all of my tests were on Server 2012 with PowerShell version 4.

Variables. You must use the FQDN of the source DC. You can substitute Days, Minutes, Years, etc, as desired for the age parameters. Modify AD component paths as desired.

Functions and requirements. The script checks to make sure that previous IFM backups exist (or don't) and checks their age to prevent running again if recently run within the age parameters. You need to be logged in to the server being promoted with credentials to perform dcpromo, and you will be prompted at the start of the script for the password to that account to remotely run the IFM backup on the source domain controller configured in the first variable. You will also be prompted for the DSRM password twice once the promotion process starts. Here is the script:

$sourcedc="" ; $sourceIFMage=(Get-Date).AddHours(-4) ; $targetIFMage=(Get-Date).AddHours(-4) ; $targetdc="$env:computername.$env:userdnsdomain" ; $session = New-PSsession -ComputerName $sourcedc -Credential $env:USERNAME ; If((Test-Path \\$sourcedc\c$\ifm) -eq $false){Invoke-Command -Session $session -ScriptBlock {cmd /c "ntdsutil "Activate Instance NTDS" "IFM" "Create Full C:\IFM" "QUIT" "QUIT""}} ; If(Test-Path \\$sourcedc\c$\ifm -OlderThan $sourceIFMage){Remove-Item \\$sourcedc\c$\ifm -recurse -confirm:$false ;Invoke-Command -Session $session -ScriptBlock {cmd /c "ntdsutil "Activate Instance NTDS" "IFM" "Create Full C:\IFM" "QUIT" "QUIT""}} ; If((Test-Path \\$targetdc\c$\ifm) -eq $false){cmd /c "xcopy \\$sourcedc\c$\ifm \\$targetdc\c$\ifm /s /i /y"} ; If(Test-Path \\$targetdc\c$\ifm -OlderThan $targetIFMage){cmd /c "xcopy \\$sourcedc\c$\ifm \\$targetdc\c$\ifm /s /i /y"} ;Remove-PSsession * ; Install-WindowsFeature -Name AD-Domain-Services –IncludeManagementTools ; Install-ADDSDomainController -domainname $env:userdnsdomain –InstallationMediaPath "c:\IFM" –DatabasePath "c:\NTDS" –SYSVOLPath "c:\SYSVOL" –LogPath "c:\NTDS" -replicationsourcedc $sourcedc -force

Yeah, one line scripts can be fairly ugly, right? But in case you were unaware, this is one method for avoiding Execution-Policy hiccups in PowerShell :)

This is not the ultimate in dcpromo scripts, but I have found it very useful when there are many of these to do and especially if you want to avoid the GUI :)

Please share your feedback and suggestions to improve it.
Happy promos!

- Peter Trast, MCITP EA, MCITP DBA, MCT LinkIn with Peter