We love template VMs. They reduce deployment time and save time when installing VMware tools and Windows Updates.
However, the critical point was Windows updates. There is a limited point in deploying from templates if they are not up-to-date with MS patches. At the same time, why waste time updating your templates manually? You can have a simple script to execute or even make it a scheduled task to convert your template VM to a VM update and then convert it back to a template. Simple? Well, yes it is.
In this script, you will need to have the password in a text file for the OS administrator account, and upon running it, it will ask for the vCenter credentials. If you wish to run it as a scheduled task, it will need updating to hold the vCenter credentials in a file as well.
# Import the PowerCLI module
Import-Module VMware.VimAutomation.Core -ErrorAction SilentlyContinue
# Connect to vCenter
connect-viserver SERVERNAME
$TeplateVMName="VM NAME"
# Convert a template to a VM
Set-Template -Template $TeplateVMName -ToVM -Confirm:$false –RunAsync
# Make a 60 seconds delay
Start-sleep -s 10
# Start the virtual machine
Start-VM -VM $TeplateVMName | Get-VMQuestion | Set-VMQuestion -DefaultOption -Confirm:$false
Start-sleep -s 120
# Get an administrator credentials from an encrypted file (if you do not want to keep the password in the PS script in clear text)
$adminname = "administrator"
$Pwd = Get-Content C:\Scripts\admin_passfile.txt | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $adminname, $Pwd
# Run the command to install all available updates in the guest OS using VMWare Tools (the update installation log is saved to a file: C:\temp\Update.log)
Invoke-VMScript -ScriptType PowerShell -ScriptText "Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot" -VM $TeplateVMName -GuestCredential $Cred | Out-file -Filepath C:\temp\VM-Update.log -Append
Start-sleep -s 800
# Update VMTools version
Update-Tools -VM $TeplateVMName -NoReboot
# Clean up the WinSxS component store and optimize the image with DISM
Invoke-VMScript -ScriptType PowerShell -ScriptText "Dism.exe /Online /Cleanup-Image /StartComponentCleanup" -VM $TeplateVMName -GuestCredential $Cred
Start-sleep -s 240
# Force restart the VM
echo "all updates done"
Restart-VMGuest -VM $TeplateVMName -Confirm:$false
Start-sleep -s 80
# Shut the VM down and convert it back to the template
Shutdown-VMGuest –VM $TeplateVMName -Confirm:$false
Start-sleep -s 80
Set-VM –VM $TeplateVMName -ToTemplate -Confirm:$false
The script above is from articles on the internet and has been modified for our use. It comes with no warranty.