Here’s my code:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,HelpMessage="Enter one or more computer name(s) and IP address(es)")]
[string[]]$ComputerName
)
Connect-VIServer -Server vcenterserver -Verbose
$TargetCluster = Get-Cluster -Location "cluster" -Verbose
$SourceVMTemplate = Get-Template -Name "Template" -Verbose
$SourceCustomSpec = Get-OSCustomizationSpec -Name "Windows 2012 R2" -Verbose
ForEach ($Computer in $ComputerName) {
Write-Verbose -Message "Preparing to deploy [$Computer]." -Verbose
$IPAddress = Read-Host -Prompt "Please enter IP Address"
$SubnetMask = Read-Host -Prompt "Please enter Subnet Mask"
$DefaultGateway = Read-Host -Prompt "Please enter Default Gateway"
$DNSServerPrimary = Read-Host -Prompt "Please enter primary DNS address"
$DNSServerSecondary = Read-Host -Prompt "Please enter secondary DNS address"
Write-Verbose -Message "Deploying Virtual Machine with Name: [$Computer] using Template: [$SourceVMTemplate] and Customization Specification: [$SourceCustomSpec] on Cluster: [$TargetCluster] and waiting for completion" -Verbose
Start-Sleep -s 60
New-VM -Name $Computer -Template $SourceVMTemplate -ResourcePool $TargetCluster -OSCustomizationSpec $SourceCustomSpec -Verbose
Write-Verbose -Message "Virtual Machine $Computer Deployed. Powering On" -Verbose
Start-Sleep -s 120
Start-VM -VM $Computer -Verbose
Start-Sleep -s 300 -Verbose
Set-OSCustomizationNicMapping -IpAddress $IPAddress -SubnetMask $SubnetMask -DefaultGateway $DefaultGateway
Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses ("$DNSServerPrimary","$DNSServerSecondary")
Stop-VM -Server $Computer
Set-NetAdapter -Name "Net adapter" -VlanID Vlan#
Start-VM -Name $Computer
}
When I run this code, I return the following error:
New-VM : 7/24/2017 2:09:59 PM New-VM Operation is not valid due to the current state of the object.
At line:19 char:13
+ New-VM -Name $Computer -Template $SourceVMTemplate -Resou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-VM], VimException
+ FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM
I’ve thrown in the Start-Sleep cmdlets for troubleshooting, but I honestly can’t figure out what is flagging the issue. Thoughts?