Image and Task Sequence Testing for Microsoft Deployment Toolkit and Hyper-V

In a previous post I wrote about my Image Factory PowerShell script for MDT. This post is about a script derived from that which I setup to test my images and my deployment task sequences. Since this script is only an edit of the previous one I don’t intend to release it “officially” on the TechNet Gallery or the PowerShell Gallery.

To explain succinctly what this script does, it turns Task Sequences into Virtual Machines.

-Mike

Follow Mike on Twitter: @Digressive

 

Features and Requirements

  • The script is designed to run on a device with MDT installed.
  • The device must also have Hyper-V management tools installed.
  • The MDT shares can be local or on a remote device.
  • The Hyper-V host can be local or on a remote device.

The script has been tested on Hyper-V installations on Windows 10, Windows Server 2016, and Windows Server 2012 R2 and MDT installations on Windows 10 and Windows Server 2016.

When run, the script will:

  1. Create and configure a Hyper-V Virtual Machine for image deployment.
  2. Boot it from the MDT LiteTouch boot media.
  3. Run the specified Task Sequence.
  4. When the TS completes, the Virtual Machine will be configured for general usage.
  5. Move on to the next specified task sequence.
  6. Do steps 1-5 for all specified TS.
  7. Optionally create a log file and email it to an address of your choice.

The script should be run with the -remote switch when the Hyper-V host is a remote device.

The script should be run with the -compat switch when the Hyper-V host a remote server running Windows Server 2012 R2.

 

Configuration

I’ve changed the configuration to be done via command line switches, instead of having to edit the script itself. Here’s a list of all the switches and example configurations

Command Line Switch Mandatory Description Example
-deploy Yes Location of the MDT deployment share. Can be the same share as the deployment share. Can be a local path or UNC. \\mdt01\deploymentshare$ OR E:\DeploymentShare
-vh Yes Name of the Hyper-V server. Can be remote or local. VS01
-vhd Yes Path relative to the Hyper-V server of where to put the VHD file for the VM(s) that will be generated D:\Hyper-V\VHD
-boot Yes Path relative to the Hyper-V server of where the ISO file is to use to boot from. F:\iso\LiteTouchPE_x64-deploy.iso
-vnic Yes Name of the virtual switch that the Virtual Machine should use to communicate with the network. If the name of the switch contains space, it should be surrounded by “double quotes”. vSwitch-Ext
-ts Yes The Task Sequence IDs from MDT that should be ran. Separate more than one with a comma [,] and no spaces. REF-W10-1703,REF-W10-1607,REF-WS2016
-l No Location to store the optional log file. The name of the log file is automatically generated. C:\Users\sysadmin\Desktop
-sendto No The email address to send the log file to. me@contoso.com
-from No* The email address that the log file should be sent from.

*This switch isn’t mandatory but is required if you wish to email the log file.

ImageFactory@contoso.com
-smtp No* SMTP server address to use for the email functionality.

*This switch isn’t mandatory but is required if you wish to email the log file.

mail01.contoso.com

OR

smtp.live.com

OR

smtp.office365.com

-user No* The username of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

example@contoso.com
-pwd No* The password required for the user being used for SMTP authentication.

*This switch isn’t mandatory but may be required depending on your SMTP server.

 

P@ssw0rd
-usessl No* Add this option if you wish to use SSL with the configured SMTP server.

Tip: If you wish to send email to outlook.com or office365.com you will need this.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

N/A
-compat No Set if the Hyper-V server is WS2012 R2 and the script is running on Windows 10 or Windows Server 2016.

This loads the older version of the Hyper-V module so it is able to manage WS2012 R2 Hyper-V VMs.

N/A
-remote No Set if the Hyper-V server is a remote device.

Do not include this switch if the script is running on the same device as Hyper-V

N/A

 

This script can be run in a variety of configurations. You could run it on a Windows 10 device with MDT and Hyper-V Management tools installed or a single MDT deployment share on a file server and a remote Hyper-V host running Windows 10, Windows Server 2016 or Windows Server 2012 R2.

The script makes changes (shown below) to your MDT customsettings.ini file – after making a backup, of course! These changes are necessary so that the process runs completely automated. Depending on your environment, you may need to make additional changes. Also most important: running this script will it will tie up your deployment share until it’s completed.

Below are the settings you’ll need to add to your Bootstrap.ini to auto login to your Build Share. I recommend make these changes for auto-login, regenerate the boot images, copying the LiteTouch.iso to a safe place, then changing the settings back to how they were. This maintains the security of your deployment share, whilst giving you the necessary automated ISO to boot from.

[Settings]
Priority=Default

[Default]
DeployRoot=\\mdt01\e$\BuildShare
UserDomain=corp.contoso.com
UserID=mdt_admin
UserPassword=P@ssw0rd
SkipBDDWelcome=YES

The script adds the following lines to the end of your customsettings.ini. It sets the current task sequence to run, tells the WinPE deployment environment to skip asking for a Task Sequence and skip asking for a computer name. The computer name and Virtual Machine name is set to the Task Sequence ID.

TaskSequenceID=$id
SkipTaskSequence=YES
SkipComputerName=YES

 

PowerShell Code


# -------------------------------------------
# Script: Image-Factory-Deploy.ps1
# Version: 2.4
# Author: Mike Galvin twitter.com/digressive
# Date: 18/08/2017
# -------------------------------------------

[CmdletBinding()]
Param(
    [parameter(Mandatory=$true)]
    [alias("deploy")]
    $mdtdeploypath,
    [parameter(Mandatory=$true)]
    [alias("ts")]
    $tsid,
    [parameter(Mandatory=$true)]
    [alias("vh")]
    $vmhost,
    [parameter(Mandatory=$true)]
    [alias("vhd")]
    $vhdpath,
    [parameter(Mandatory=$true)]
    [alias("boot")]
    $bootmedia,
    [parameter(Mandatory=$true)]
    [alias("vnic")]
<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>    $vmnic,
    [alias("l")]
    $logpath,
    [alias("sendto")]
    $mailto,
    [alias("from")]
    $mailfrom,
    [alias("smtp")]
    $smtpserver,
    [alias("user")]
    $smtpuser,
    [alias("pwd")]
    $smtppwd,
    [switch]$usessl,
    [switch]$compat,
    [switch]$remote)

## If logging is configured, start log
If ($LogPath) {
    $LogFile = "image-factory.log"
    $Log = "$LogPath\$LogFile"
    $LogT = Test-Path -Path $Log

## If the log file already exists, clear it
    If ($LogT) {
        Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Value "****************************************"
    Add-Content -Path $Log -Value "$(Get-Date -format g) Log started"
    Add-Content -Path $Log -Value ""
}

## If compat is configured, load the older Hyper-V PS module
If ($compat) {
    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Importing Hyper-V 1.1 PowerShell Module"
    }
    Write-Host "$(Get-Date -format g) Importing Hyper-V 1.1 PowerShell Module"
    Import-Module $env:windir\System32\WindowsPowerShell\v1.0\Modules\Hyper-V\1.1\Hyper-V.psd1
}

## Import MDT PS module
If ($LogPath) {
    Add-Content -Path $Log -Value "$(Get-Date -format g) Importing MDT PowerShell Module"
}
Write-Host "$(Get-Date -format g) Importing MDT PowerShell Module"
$mdt = "$env:programfiles\Microsoft Deployment Toolkit\bin\MicrosoftDeploymentToolkit.psd1"
Import-Module $mdt

ForEach ($id in $tsid) {
    ## Setup MDT custom settings for VM auto deploy
    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Backing up current MDT CustomSettings.ini"
    }
    Write-Host "$(Get-Date -format g) Backing up current MDT CustomSettings.ini"

    Copy-Item $mdtdeploypath\Control\CustomSettings.ini $mdtdeploypath\Control\CustomSettings-backup.ini
    Start-Sleep -s 5

    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Setting up MDT CustomSettings.ini for Task Sequence ID: $id"
    }
    Write-Host "$(Get-Date -format g) Setting MDT CustomSettings.ini for Task Sequence ID: $id"

    Add-Content $mdtdeploypath\Control\CustomSettings.ini "TaskSequenceID=$id"
    Add-Content $mdtdeploypath\Control\CustomSettings.ini "SkipTaskSequence=YES"
    Add-Content $mdtdeploypath\Control\CustomSettings.ini "SkipComputerName=YES"

    ## Create VM
    $vmname = $id

    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Creating VM: $vmname on $vmhost"
        Add-Content -Path $Log -Value "$(Get-Date -format g) Adding VHD: $vhdpath\$vmname.vhdx"
        Add-Content -Path $Log -Value "$(Get-Date -format g) Adding Virtual NIC: $vmnic"
    }
    Write-Host "$(Get-Date -format g) Creating VM: $vmname on $vmhost"
    Write-Host "$(Get-Date -format g) Adding VHD: $vhdpath\$vmname.vhdx"
    Write-Host "$(Get-Date -format g) Adding Virtual NIC: $vmnic"

    New-VM -name $vmname -MemoryStartupBytes 4096MB -BootDevice CD -Generation 1 -NewVHDPath $vhdpath\$vmname.vhdx -NewVHDSizeBytes 130048MB -SwitchName $vmnic -ComputerName $vmhost

    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Configuring VM Processor Count"
        Add-Content -Path $Log -Value "$(Get-Date -format g) Configuring VM Static Memory"
        Add-Content -Path $Log -Value "$(Get-Date -format g) Configuring VM to boot from $bootmedia"
    }
    Write-Host "$(Get-Date -format g) Configuring VM Processor Count"
    Write-Host "$(Get-Date -format g) Configuring VM Static Memory"
    Write-Host "$(Get-Date -format g) Configuring VM to boot from $bootmedia"

    Set-VM $vmname -ProcessorCount 2 -StaticMemory -ComputerName $vmhost
    Set-VMDvdDrive -VMName $vmname -ControllerNumber 1 -ControllerLocation 0 -Path $bootmedia -ComputerName $vmhost

    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Starting $vmname on $vmhost with $id"
    }
    Write-Host "$(Get-Date -format g) Starting $vmname on $vmhost with $id"

    Start-VM $vmname -ComputerName $vmhost

    ## Wait for VM to stop
    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Waiting for $vmname to build $id"
    }
    Write-Host "$(Get-Date -format g) Waiting for $vmname to build $id"

    While ((Get-VM -Name $vmname -ComputerName $vmhost).state -ne 'Off') {Start-Sleep -s 5}

    ## Change config back
    Set-VMDvdDrive -VMName $vmname -ControllerNumber 1 -ControllerLocation 0 -Path $null -ComputerName $vmhost
    Set-VM -Name $VMName -DynamicMemory -MemoryStartupBytes 1GB -MemoryMinimumBytes 100MB -MemoryMaximumBytes 4GB -ComputerName $vmhost

    ## Restore MDT custom settings
    If ($LogPath) {
        Add-Content -Path $Log -Value "$(Get-Date -format g) Restoring MDT CustomSettings.ini from backup"
    }
    Write-Host "$(Get-Date -format g) Restoring MDT CustomSettings.ini from backup"

    Remove-Item $mdtdeploypath\Control\CustomSettings.ini
    Move-Item $mdtdeploypath\Control\CustomSettings-backup.ini $mdtdeploypath\Control\CustomSettings.ini
    Start-Sleep -s 5
}


## If log was configured stop the log
If ($LogPath) {
    Add-Content -Path $Log -Value ""
    Add-Content -Path $Log -Value "$(Get-Date -format g) Log finished"
    Add-Content -Path $Log -Value "****************************************"

    ## If email was configured, set the variables for the email subject and body
    If ($smtpserver) {
        $mailsubject = "Lab: Image Factory Deploy Log"
        $mailbody = Get-Content -Path $log | Out-String

        ## If an email password was configured, create a variable with the username and password
        If ($smtppwd) {
            $smtpcreds = New-Object System.Management.Automation.PSCredential -ArgumentList $smtpuser, $($smtppwd | ConvertTo-SecureString -AsPlainText -Force)

            ## If ssl was configured, send the email with ssl
            If ($usessl) {
                Send-MailMessage -To $mailto -From $mailfrom -Subject $mailsubject -Body $mailbody -SmtpServer $smtpserver -UseSsl -Credential $smtpcreds
            }

            ## If ssl wasn't configured, send the email without ssl
            Else {
                Send-MailMessage -To $mailto -From $mailfrom -Subject $mailsubject -Body $mailbody -SmtpServer $smtpserver -Credential $smtpcreds
            }
        }

        ## If an email username and password were not configured, send the email without authentication
        Else {
            Send-MailMessage -To $mailto -From $mailfrom -Subject $mailsubject -Body $mailbody -SmtpServer $smtpserver
        }
    }
}

## End

2 Comments Add yours

  1. DesarX says:

    Hi,
    Is possible public list for apps secure remove from install.wim but to work store app… and how to stop onedrive installer start when start system welcome screen
    Thanks

    Like

  2. Thatt is a great tip particularly to those neww to the blogosphere.
    Simple but verry accurate info… Thank you for sharing this one.

    A must read article!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.