I would like to fire up a couple of localy stored *.cmd files on a newly deployed server. Can I solve it like this? Also, how can I
make the vm to reboot after every execution of the both cmd:s?
### DEFINE POWERSHELL SCRIPTS TO RUN IN VM AFTER DEPLOYMENT ############################################################################################################
if ($IP) {
Add-Script "New-NetIPAddress -IPAddress $IP -PrefixLength 16 -DefaultGateway $GW -InterfaceIndex (Get-NetAdapter).InterfaceIndex"
}
$script = "C:\Automation\script1.cmd"
$script = "C:\Automation\script2.cmd"
### DEPLOY VM ###############################################################################################################################################################
Write-Host "Deploying Virtual Machine with Name: [$Hostname] using Template: [$SourceVMTemplate] and Customization Specification: [$SourceCustomSpec] on cluster: [$cluster]"
$vm = New-VM -Name $Hostname -Template $SourceVMTemplate -ResourcePool $cluster -OSCustomizationSpec $SourceCustomSpec -Location $Location -Datastore $Datastore -DiskStorageFormat $DiskStorageFormat
Set-VM -VM $vm -NumCpu $CPU -MemoryGB $Memory -Confirm:$false
Get-VM $Hostname | Get-HardDisk | Where-Object {$_.Name -eq "Hard Disk 1"} | Set-HardDisk -CapacityGB $DiskCapacity -Confirm:$false
if($diskSizes.Count -gt 0){
$diskSizes | %{
New-HardDisk -VM $vm -CapacityGB $_ -StorageFormat Thin | New-ScsiController -Type ParaVirtual -Confirm:$false
}
}
Write-Host "Virtual Machine $Hostname Deployed. Powering On"
Start-VM -VM $Hostname
if (-not (Check-CustomizationStarted $Hostname)) { break }; if (-not (Check-CustomizatonFinished $Hostname)) { break }
foreach ($script in $scripts)
{
Invoke-VMScript -ScriptText $script[0] -VM $Hostname -GuestCredential $VMLocalCredential
}
New-TagAssignment -Entity $vm -Tag DailyBackup
Restart-VM $Hostname
### END OF SCRIPT ##############################
Write-Host "Deployment of VM $Hostname is finished"
Yes, you can use the Invoke-VMScript cmdlet for that.
You can use the Restart-VMGuest cmdlet inside your foreach loop after each Invoke-VMScript to restart the VM.
Just make sure to only continue after the VMware Tools are ready again.
See for example Re: Windows server cloning, how to automate joining domain how to test for this in a loop.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference