Skip to content

Instantly share code, notes, and snippets.

@txag1995
Last active March 12, 2017 21:28
Show Gist options
  • Save txag1995/73e2473d698c3b7d5d1d to your computer and use it in GitHub Desktop.
Save txag1995/73e2473d698c3b7d5d1d to your computer and use it in GitHub Desktop.
PowerCLI Example
$Server = "VCENTER SERVER"
$datacenter = Get-Datacenter -Name "DATACENTER NAME"
$cluster = Get-Cluster -Name "CLUSTER NAME" -Location $datacenter
$TemplateName = "TEMPLATE NAME"
$Template = Get-Template -Name $TemplateName -Location $datacenter
$Datastore = Get-DatastoreCluster -Name "DATASTORE NAME"
$ResourcePool = Get-ResourcePool -Name "RESOURCE POOL NAME" -Location $cluster
$folder = "FOLDER NAME"
$vmname = "VM NAME"
$OSType = "Windows"
$OSCSType = "NonPersistent"
$DNSSuffix = "DNS SUFFIX"
$OrgName = "COMPANY NAME"
$AdminPwd = "LOCAL ADMIN PASSWORD"
$TimeZone = "004"
$AutoLogonCount = 0
$ProductKey = "D2N9P-3P6X9-2R39C-7RTCD-MDVJX" # Generic KMS Client Key
$DNSServer = "DNS IP"
$DomainUser = "DOMAIN USER FOR JOINING"
$DomainPass = "DOMAIN PASS FOR JOINING"
$OSCS = New-OSCustomizationSpec `
-OSType $OSType `
-NamingScheme Fixed `
-NamingPrefix $vmame `
-Type OSCSType `
-DNSSuffix $DNSSuffix `
-Domain $DNSSuffix `
-OrgName $OrgName `
-ChangeSid `
-AdminPassword $AdminPwd `
-FullName $OrgName `
-TimeZone $TimeZone `
-AutoLogonCount $AutoLogonCount `
-ProductKey $ProductKey `
-DnsServer $DNSServer `
-DomainUsername $DomainUser `
-DomainPass $DomainPass
$NewVM = New-VM `
-Name $vmname `
-ResourcePool $ResourcePool `
-Template $Template `
-Datastore $Datastore `
-DiskStorageFormat Thin `
-Location $folder `
-OSCustomizationSpec $OSCS
Start-VM -VM $NewVM
# Wait for customization to complete. Wait up to 3 minutes. Typically it takes about 2 minutes.
$timeout = 0
$customization_complete = $null
do {
Write-Host "Waiting for OSCustomization to complete..."
$customization_complete = Get-VIEvent -Entity $NewVM -Username "User" | Where-Object {$_.FullFormattedMessage -match "Customization of VM $($NewVM.Name) succeeded"}
sleep 5
$timeout +=1
} while ($customization_complete -eq $null -and $timeout -lt 36)
if ($timeout -ge 36) {
throw "OS Customization failed to complete after 3 minutes"
}
else {
Write-Host "OSCustomization completed successfully!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment