Below is a working example of a script to create a Vm from a template, using Local OSCustomizationSpec
Script is created using PowerCLI in PowerShell 2.0 ISE
The script although has some code to support Linux also but its not working. If anyone is able to make it work then please post it.
Although I have used OSCustomizationSpecs and its working for my need also; but you will more than many people who would prefer using VM-Invoke for the operations needed on VM /or create a script for required operation on the template and then Invoke the script. This looks a better way if you wish to make your script scalable for future.
Please post your comment / questions about this post.
#-----------------------------------------------------------------------------------------------------------------------------------------------------#
$Report = ""
#Import vm name from csv file
Import-Csv $csvFile |
foreach {
$strNewVMName = $_.vmname
$strTemplate = $_.template
$notes = $_.notes
$ostype = $_.ostype
write-host "Starting ++++++++ Creating $strNewVMName from $strTemplate of type $ostype"
if ($ostype.CompareTo("Windows") -eq 0)
{
# New-OSCustomizationSpec -FullName-OrgName[-OSType] [-ChangeSid] [-DeleteAccounts] [-Server]
# [-Name] [-Type] [-DnsServer] [-DnsSuffix] [-GuiRunOnce]
# [-AdminPassword] [-TimeZone] [-AutoLogonCount] [-Domain] [-Workgroup]
# [-DomainCredentials] [-DomainUsername] [-DomainPassword] [-ProductKey] [-NamingScheme]
# [-NamingPrefix] [-Description] [-LicenseMode] [-LicenseMaxConnections]
# [-WhatIf] [-Confirm] []
$strCustomSpec = New-OSCustomizationSpec -FullName Administrator -OrgName "CA Technologies" -OSType $ostype -ChangeSid `
-Name $strNewVMName -Type NonPersistent -AdminPassword interOP@123 -TimeZone India -Workgroup WORKGROUP -NamingScheme Fixed `
-NamingPrefix $strNewVMName -LicenseMode PerServer -LicenseMaxConnections 5 -Confirm:$false
}
elseif ($ostype.CompareTo("Linux") -eq 0)
{
# New-OSCustomizationSpec [-OSType] [-Server ] [-Name] [-Type ] [-DnsServer]
# [-DnsSuffix] [-Domain] [-NamingScheme ] [-NamingPrefix] [-Description ]
# [-WhatIf] [-Confirm] []
$strCustomSpec = New-OSCustomizationSpec -OSType $ostype -Name $strNewVMName -Type NonPersistent `
-NamingScheme Fixed -NamingPrefix $strNewVMName -Confirm:$false
}
else
{
"In-correct OS Type - $ostype "
return
}
"OSCustomizationSpec to be Used is :- "
write-output $strCustomSpec
$vmhost = Get-VMHost -Name $vmhost
$newVM = New-VM -Name $strNewVMName -Template $(get-template $strTemplate) -VMHost $vmhost `
-OSCustomizationSpec $strCustomSpec -Confirm:$false -Notes $notes -WhatIf
Start-Sleep -s 30
Start-VM -RunAsync -Confirm:$false -VM $strNewVMName
Remove-OSCustomizationSpec -CustomizationSpec $strCustomSpec -Confirm:$false
write-host "Completed ++++++++ Creating $strNewVMName from $strTemplate of type $ostype"
$Report += $strNewVMName + ", "
}
write-host "$Report - Done!"