MSEndpointMgr

Completely automate the Reference Image creation process

This blog post will help you setup a process to completely automate the reference image creation using MDT. It will assume that you have prior knowledge of MDT, since not all steps will be described in detail.

Environment setup

  • MDT01 – Windows Server 2012 running Microsoft Deployment Toolkit 2012 Update 1 and Windows Server Update Services 4.0
  • LAB01 – Windows Server 2012 running Hyper-V
  • MGMT01 – Windows Server 2012 running the scheduled task

You’d of course need a working environment with Active Directory and DNS, but that’s not covered in the scope of this blog post.

Process overview
Phase 1 – A scheduled task will every third month kick off a PowerShell script.
Phase 2 – That PowerShell script will create a virtual machine and send an email teling the process has begun. The virtual machine gets configured to boot from the LiteTouchPE_x64.iso file.
Phase 3 – A custom created task sequence in MDT will install Windows 7 Enterprise SP1 x64. Additionally updates will be applied during the task sequence.
Phase 4 – When the task sequence is finished, an email will be sent telling that the process has finished and the newly created reference image has been created.

Create the MDT user account

Create a user account in Active Directory called MDTAdmin and give the user a proper password. In this scenario we’re going to use P@$$w0rd.

Create the reference image folder

1. Create a new folder your Configuration Manager 2012 Primary site and call it RefImages.
2. Right click on the folder and choose Properties.
3. Click Edit and then Add. Type in MDTAdmin and click OK.
4. Check Full Control and click OK and OK again.

 

The PowerShell scripts

We’ll be using two PowerShell scripts.

Script 1 – CreateCaptureVM.ps1
The first script is the one that creates the virtual machine:

#Variables for VM configuration
$HostName = "LAB01.domain.com"
$SRV = "CAPTURE01"
$RAM = 2GB
$DISK = 200GB
$NETWORK = "<name of the virtual switch in Hyper-v>"
$ISO = "D:\BootImages\LiteTouchPE_x64.iso"
$VMSearch = $SRV
#Remove any existing VM's with name matching in $SRV
if ($VMSearch -eq $SRV) {
if ((Get-VM -ComputerName $HostName -Name $SRV -ErrorAction SilentlyContinue).State -eq "Running") {
Send-MailMessage -SmtpServer "<smtp server>" -From "[email protected]" -To "[email protected]" -Subject "Reference Image creation previous attempt failed" -Body "Something went wrong with the last reference image capture process. Please connect to CAPTURE01 on LAB01.domain.com and solve any issues."
exit
}
Remove-VM -Name $SRV -ComputerName $HostName -Force -ErrorAction SilentlyContinue
$VHDSearch = Get-ChildItem -Name CAPTURE01* -Path "\\$HostName\D$\" -Recurse -ErrorAction SilentlyContinue
$VHDPath = "\\$HostName\D$\" + $VHDSearch
Write-Host "Path >>" $VHDPath
if ($VHDPath -match ".VHDX") {
Remove-Item $VHDPath -Force
}
else {
}
}#Create a new VM with specified configuration
New-VM -Name $SRV -ComputerName $HostName -MemoryStartupBytes $RAM -NewVHDPath "CAPTURE01.VHDX" -NewVHDSizeBytes $DISK -SwitchName $NETWORK
#Enable VLAN ID for the VM's network adapter, this can be commented out if you don't require VLAN for your VM
Set-VMNetworkAdapterVlan -ComputerName $HostName -VMName $SRV -Access -VlanId 3141
#Load boot ISO
Set-VMDvdDrive -ComputerName $HostName -VMName $SRV -Path $ISO
#Start VM
Start-VM -ComputerName $HostName -Name $SRV
#Email [email protected] informing that the reference image creation has begun as scheduled
Send-MailMessage -SmtpServer "<smtp server>" -From "[email protected]" -To "[email protected]" -Subject "Reference Image creation has begun" -Body "Please monitor for an email in about 2-3 hours telling that the reference image creation process has successfully finished."

Script 2 – OSDInstallComplete.ps1

The second script is the one that will send an email to the receiver when the task sequence is complete:

Send-MailMessage "<smtp server>" -From "[email protected]" -To "[email protected]" -Subject "Reference Image creation has successfully finished" -Body "Please rename the newly created Win7SP1RefImage.wim to Win7SP1vXRefImage.wim and import it into Configuration Manager 2012."

Create the scheduled task

Open Task Scheduler on MGMT01 and create a new task. Configure it as you like, but the Action should look like this:

 
Press OK and when prompted with:

Press Yes.
I’ve configured the scheduled task to run on the last Thursday each March, June, September and December.

Configure WSUS automatic approval and synchronization schedule

Open up the Update Services console on MDT01 and go to Options. Configure the Synchronization Schedule to automatic. Then configure the Automatic Approvals according to the picture below:

Start a manual synchronization so that the WSUS database has the meta data of any available updates.

MDT Deployment Share creation and Rules setup

1. Open Deployment Workbench on MDT01.
2. Right click on Deployment Shares and choose New Deployment Share.
3. Enter C:\DeploymentShare as the path for this deployment share and click Next.
4. Choose the default share name suggested (DeploymentShare$) and click Next.
5. Choose the default deployment share description (MDT Deployment Share) and click Next.
6. Uncheck all questions on the Options page and click Next.
7. Finish the wizard and close it.
8. Open Properties for the new deployment share and click on the Windows PE tab.
9. Select Platform x64 and make sure that Generate a Lite Touch bootable ISO image is checked.
10. Under the Features tab of the Windows PE tab, check .NET Framework 4 and Windows PowerShell 3.0.

5. Go to the Rules tab and paste in the rules from the section below. Remember to change the lines in RED so that it will work in your environment.

[Settings]
Priority=Default
Properties=MyCustomProperty
[Default]
OSInstall=Y
DeploymentType=NEWCOMPUTER
UserID=mdtadmin
UserDomain=domain.com
UserPassword=P@$$w0rd
SkipBDDWelcome=YES
SkipDeploymentType=YES
SkipDomainMembership=YES
SkipApplications=YES
SkipSummary=YES
SkipUserData=YES
SkipComputerName=YES
SkipTaskSequence=YES
SkipLocaleSelection=YES
SkipTimeZone=YES
SkipAppsOnUpgrade=YES
SkipAdminPassword=YES
SkipProductKey=YES
SkipComputerBackup=YES
SkipBitLocker=YES
SkipCapture=YES
SkipFinalSummary=YES
ComputerName=WIN7REF
UILanguage=en-US
UserLocale=en-US
KeyboardLocale=0409:00000409
TimeZoneName=W. Europe Standard Time
TaskSequenceID=WIN7REF
WSUSServer=https://mdt01.domain.com:8530
DoCapture=YES
ComputerBackupLocation=NETWORK
BackupShare=\\mdt01.domain.com\OSDDeployment
BackupDir=RefImages
BackupFile=Win7SP1RefImage.wim
FinishAction=SHUTDOWN

6. Apply the changes made in the Properties window and press OK.
7. Right click on Operating Systems under your deployment share, and choose Import Operating System.
8. Select Full set of source files. Click Next.
9. Specify the source files for a Windows 7 Enterprise SP1 x64. Select Move the files to the deployment share instead of copying them.
10. Specify a name for the directory that will be created in the deployment share, where the source files will be moved to.
11. Finish the wizard by clicking Next.
12. Right click on your deployment share and click Update Deployment Share.
13.  Choose Completely regenerate the boot images and click Next until the wizard finishes.
For this blog post, I’ll not be describing how to add any applications to your reference image creation process. That will be covered in a later post.

Give permissions to MDTAdmin on C:\DeploymentShare

1. Browse to C:\DeploymentShare.
2. Right click on the folder and choose Properties.
3. Click Edit and then Add. Type in MDTAdmin and click OK.
4. Check Full Control and click OK and OK again.

MDT bootstrap.ini configuration

1. Open the properties for the deployment share and go to the Rules tab.
2. Click on the Edit Bootstrap.ini button.

3.  The bootstrap.ini should look like this:

[Settings]
Priority=Default
[Default]
DeployRoot=\\MDT01.domain.com\DeploymentShare$
SkipBDDWelcome=Yes
UserID=mdtadmin
UserDomain=domain.com
UserPassword=P@$$w0rd

MDT Task Sequence creation

1. Right click on Task Sequences under your deployment share, and choose New Task Sequence.
2. Enter WIN7REF under Task sequence ID.
3. Enter your preferred name under Task sequence name and click Next.
4. Select the Standard Client Task Sequence as your template and click Next.
5. Choose the Operating System that we imported previously and click Next.
6. Select Do not specify a product key at this time and click Next.
7. Enter your organization into the Organization field, but leave the Full Name and Internet Explorer Home Page values by default (you can change them if’d like) and click Next.
8. Specify an Administrator password and click Next.
9.  Click Next again and finish the wizard.

MDT Task Sequence configuration

1. Go to Task Sequences under the deployment share, and open the properties for the newly created task sequence.
2. Go to the Task Sequence tab. Under State Restore, enable Windows Update (PreApplication Installation) and Windows Update (Post-Application Installation). You can enable a step by selecting it and clicking on the Options tab for that step, then uncheck the Disable this step. It’s a good idea to enable both Windows Update steps, if you plan to install application in your reference image. But as I said earlier, the scope of this post will not go through installing applications in the reference image.
3. Disable these steps, BitLockerRestore User StateRestore Groups and Apply Local GPO Packages. They are all found under the State Restore group.
4. Select the Imaging group, and click on Add. Select New Group and name it Custom – Finish action.
5. Select the newly created Custom – Finish action group and click Add – General – Run PowerShell Script.
6. Change the name of the Run PowerShell Script step to Run OSDInstallComplete. In the PowerShell script field, enter %SCRIPTROOT%\OSDInstallComplete.ps1. Leave the Parameters field empty.
7. Click OK in the task sequence window.

Copy CreateCaptureVM.ps1 to MGMT01

1. On MGMT01, open PowerShell ISE and create a new file.
2. Copy the code from Script 1 into PowerShell ISE.
3. Make changes to the script marked in RED, so that it works in your environment.
4. Save the file to C:\Scripts as CreateCaptureVM.ps1.

Copy OSDInstallComplete.ps1 to the deployment share

1. On MDT01, open PowerShell ISE and create a new file.
2. Copy the code from Script 2 into PowerShell ISE.
3. Make changes to the script marked in RED, so that it works in your environment.
4. Save the file on MDT01 under C:\DeploymentShare\Scripts. Note that this is the path to the deployment share that you created earlier. What’s important is that you save the file in the Scripts folder of your deployment share, if you chose another path.

Update the deployment share

1. Right click on your deployment share and choose Update Deployment Share.
2. Select Completely regenerate the boot images and click Next.

3. Click Next again and wait for the wizard to finish.

Copy the LiteTouchPE_x64.iso to LAB01

1. On MDT01, browse to C:\DeploymentShare\Boot.

2. Copy the LiteTouchPE_x64.iso file to D:\BootImages on LAB01. If you don’t have a D:\ drive, that’s fine. Just place it somewhere else but remember to change the $ISO variable in Script 1.

Let’s start the reference image process

1. On MGMT01, open Task Scheduler and browse to your scheduled task we created in the beginning.
2. Right click on the scheduled task and choose Run.

The CAPTURE01 virtual machine will now be created on LAB01 and automatically start with the LiteTouchPE_x64.iso file loaded into the CM-ROM drive. After a few minutes the you’ll see that it’s applying the OS:

Once done, the virtual machine will boot into the OS and apply Windows Updates:

When all the updates have been installed, the task sequence will then reboot into Windows PE, capture the OS and finally upload the reference image to the specified folder in CustomSettings.ini:

When the whole process is complete, an email will be sent out informing that the newly created reference image has been uploaded and is ready to be imported into Configuration Manager.
That’s it!

Nickolaj Andersen

Chief Technical Architect and Enterprise Mobility MVP since 2016. Nickolaj has been in the IT industry for the past 10 years specializing in Enterprise Mobility and Security, Windows devices and deployments including automation. Awarded as PowerShell Hero in 2015 by the community for his script and tools contributions. Creator of ConfigMgr Prerequisites Tool, ConfigMgr OSD FrontEnd, ConfigMgr WebService to name a few. Frequent speaker at conferences such as Microsoft Ignite, NIC Conference and IT/Dev Connections including nordic user groups.

17 comments

  • Is there any reason that you couldn’t use a customize WIM file for this, instead of using the base Windows OS?

  • Hi Nicolaj,
    First of all, thank you for an awesome site 🙂
    How would you automate the process if you are building reference images for both OS and servers ? you would need a deployment share for each different OS right ?

    • Hi Peter,
      I’d not create different deployment shares. You can target a specific TS by a VM’s MAC address in CustomSettings.ini. Something like this for instance:
      [Settings]
      Priority=MacAddress, Default
      Properties=MyCustomProperty
      [00:15:5D:00:00:00]
      TaskSequenceID=W10X641607
      Regards,
      Nickolaj

  • Hi,
    Why would one automate the image creation process? Is it not easier to manually create an image, sysprep it then capture?
    Just trying to understand what the benefits are.
    Thanks

    • Hi Tom,
      Wouldn’t you agree that the benefits are pretty obvious if you have an automated process that on a monthly basis gives you a WIM file that’s ready to be imported and tested in your environment, instead of you performing the same tasks manually? You’d be able to focus on stuff that’s more important.
      Regards,
      Nickolaj

      • Hi Nickolaj,
        Yes, after playing around it does make sense. I was definitely looking at it from the wrong angle.
        I took the view that the image creation process was a one off, however by following your guide and actually ‘doing it’ over and over, it has made it much more obvious 🙂
        Thanks

  • HI,
    Great stuff!
    I have one problem, i tried the script and it creates the VM and starts off the ts.
    BUt when i shutdown the vm after the capture is done i tried to start the script again and see if it cleans the vm and creata a new one. It removes the vm from hyper-v but it doesn’t remove the.vhdx hdd attached to it. Then it dosen’t create a new VM and kick off the ts. Probably because it failes with removing the old .vhdx. Any tips?

  • Hi Nickolaj,
    i specified DOCAPTURE=YES AND SKIPCAPTURE=YES and other necesarry variables but my Tasksequence (Standard Client Task Sequence ) never reaches Imaging-Level. It ends successful before and i cant find any errors in the Log-Files.
    You have any Idea why?

    • I figured it out myself: the variable docapture doesn’t work.
      I disables the “equals to YES” Condition in the TS .
      Now Sysprep and capturing starts, but the docapture=yes variable is in the cs.ini… idk

      • found my mistake, i specified the Task-sequence Name and not the Task sequence ID in the cs.ini omg….
        never name them different again…awkward… *facepalm*

  • Do you see any reason this wouldn’t work with some minor tweaks if using 2008r2 Hyper-V instead of 2012 Hyper-V?

    • Hi Matt,
      Not really, but you’d need to verify that the PowerShell script works (which it most likely wont) 🙂
      If you get it to work, I’d be glad if you’re able to share your findings here so that if there’s any other out there dealing with the same problem they could also leverage from your solution.
      On a side note, I’d strongly consider upgrading the Hyper-V host though at any given time.
      Regards,
      Nickolaj

Sponsors