Quantcast
Channel: Kasraeian » Start-VM
Viewing all articles
Browse latest Browse all 3

Using VMware PowerCLI (#006) – Deploy Template (v0.4)

0
0

I’ve edited “DTS (v0.3)” so it can generate “.csv” and accept input from “.csv” file as well.
Feel free to send your comment and idea and if you find any bug/problem in this script please let me know, I hope this version can do better work and be useful.

Download89 downloads
#####################################################
function Header {
	CLS
	Write-Host "Name:`tDeploy Template Script (v0.4)"
}
#####################################################

# Adding PSSnapin
$pssnap = Get-PSSnapin | Sort-Object Name
$APS = "No"
$PSIndex = 1
1..$pssnap.Count | foreach {
	if ($pssnap[$PSIndex].Name -like "vmware.vimautomation.core") {
		$APS = "Yes"
	}
	$PSIndex++
}
if ($APS -eq "No") {
	Write-Host "Adding required PowerShell Snapin"
	Add-PSSnapin VMware.VimAutomation.Core
}

# Enabling multiple connection
$PCC = get-PowerCLIConfiguration
if ($test.DefaultVIServerMode -eq "single") {
	Write-Host "Changing `"Default VI Server Mode`""
	Set-PowerCLIConfiguration -DefaultVIServerMode Multiple
}

# vCenter Server Connection
Header
Write-Host ""
$Target = Read-Host ("Which vCenter Do you want connect to")
if ($global:DefaultVIServer.Name -eq $Target) {
	$CRMB = "Yes"
} else {
	$VICSI = Get-VICredentialStoreItem | Sort-Object Host
	$AI = "No"
	foreach ($item in $VICSI) {
		if ($Target -eq $item.Host) {
			$AI = "Yes"
		}
	}
	if ($AI -eq "No") {
		$cred = Get-Credential
		Write-Host "Connecting to $Target"
		$NCR = Connect-VIServer -Server $Target -Credential $cred
	} else {
		Write-Host "Connecting to $Target"
		$NCR = Connect-VIServer -Server $Target
	}
	if ($NCR.IsConnected -eq $true) {
		$CRMB = "Yes"
	} else {
		$CRMB = "No"
	}
}

# Automated Mode functions and process
function AutomatedMode {
	Header
	Write-Host "`nFor automated mode you need to present `".csv`" file in bellow format`nName,Template,VMHost,Datastore,ResourcePool,vApp,CustomizationProfile,StartState"
	$AFEA = Read-Host ("`nDo you have csv file matching above format (Y/N) [default = N]")
	Switch ($AFEA) {
		"y" {
			$CFP = Read-Host ("Please give the full path of `".csv`" file")
			if ($CFP -notlike "") {
				Import-Csv -Path $CFP | foreach {
					if ($($_.Name) -and $($_.Template) -and $($_.VMHost) -and $($_.Datastore) -notlike "") {
						if ($_.StartState -eq "Yes") {
							if ($_.CustomizationProfile -notlike "" -and $_.CustomizationProfile -notlike "none") {
								if ($($_.ResourcePool) -notlike "" -and $($_.ResourcePool) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -OSCustomizationSpec $($_.CustomizationProfile) -ResourcePool $($_.ResourcePool) | Start-VM
								} elseif ($($_.vApp) -notlike "" -and $($_.vApp) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -OSCustomizationSpec $($_.CustomizationProfile) | Move-VM -Destination $($_.vApp) | Start-VM
								} else {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -OSCustomizationSpec $($_.CustomizationProfile) | Start-VM
								}
							} else {
								if ($($_.ResourcePool) -notlike "" -and $($_.ResourcePool) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -ResourcePool $($_.ResourcePool) | Start-VM
								} elseif ($($_.vApp) -notlike "" -and $($_.vApp) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) | Move-VM -Destination $($_.vApp) | Start-VM
								} else {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) | Start-VM
								}
							}
						} else {
							if ($_.CustomizationProfile -notlike "" -and $_.CustomizationProfile -notlike "none") {
								if ($($_.ResourcePool) -notlike "" -and $($_.ResourcePool) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -OSCustomizationSpec $($_.CustomizationProfile) -ResourcePool $($_.ResourcePool)
								} elseif ($($_.vApp) -notlike "" -and $($_.vApp) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -OSCustomizationSpec $($_.CustomizationProfile) | Move-VM -Destination $($_.vApp)
								} else {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -OSCustomizationSpec $($_.CustomizationProfile)
								}
							} else {
								if ($($_.ResourcePool) -notlike "" -and $($_.ResourcePool) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) -ResourcePool $($_.ResourcePool)
								} elseif ($($_.vApp) -notlike "" -and $($_.vApp) -notlike "none") {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore) | Move-VM -Destination $($_.vApp)
								} else {
									New-VM -Name $($_.Name) -Template $($_.Template) -VMHost $($_.VMHost) -Datastore $($_.Datastore)
								}
							}
						}
					}
				}
				$TOS = Read-Host ("Would you like to create other series (Y/N)")
				if ($TOS -like "y") {
					MainBody{}
				} else {
					Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
					Exit
				}
			} else {
				Write-Host ("`nProvided information is not correct") -BackgroundColor Yellow -ForegroundColor DarkRed
				$Answer = Read-Host ("`nDo you want to try again (Y/N) [default = Y]")
				Switch ($Answer) {
					"n" {
						Header
						Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
						Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
						Exit
					}
					default {
						AutomatedMode{}
					}
				}
			}
		}
		default {
			Header
			$CNCFA = Read-Host ("`n[M] Manually create new `".csv`" file`n[Other keys] Exit`nPlease select from above items [default = Exit]")
			Switch ($CNCFA) {
				"m" {
					Header
					Write-Host "`nPlease provide below information, items with * are required in order to create new series of VMs"
					$Name = Read-Host ("Please enter naming patern*")
					$Template = Read-Host ("Please enter source template name*")
					$VMHost = Read-Host ("Please define target host*")
					$Datastore = Read-Host ("Please define target datastore*")
					$ResourcePool = Read-Host ("Please enter resource pool to place new VM(s)")
					$vApp = Read-Host ("Please enter vApp to place new VM(s)")
					$OSCP = Read-Host ("Please select OS customization specification")
					$StartState = Read-Host ("Please type `"Yes`" if you want to power on your VMs after their creation or `"No`" for manual process")
					$Qty = Read-Host ("How many VM(s) do you want to deploy")
					$SCF = Read-Host ("Please provide full address to save csv file")
					if ($Qty -ge 1) {
					    if ($Name -and $Template -and $VMHost -and $Datastore -and $SCF -notlike "") {
					        $i = 1
					        $FileContent = "Name,Template,VMHost,Datastore,ResourcePool,vApp,CustomizationProfile,StartState"
					        1..$Qty | foreach {
					            $NewContent = "`n$Name$i,$Template,$VMHost,$Datastore,$ResourcePool,$vApp,$OSCP,$StartState"
					            $FileContent = $FileContent + $NewContent
					            $i++
					        }
							Header
							Write-Host "`nNew `".csv`" file would be create containing bellow information on $SCF`n"
					        $FileContent
							$WCFA = Read-Host ("`nDo you want to save these information (Y/N)")
							Switch ($WCFA) {
								"y" {
									$FileContent | Out-File $SCF
								}
								"n" {
									$RWPA = Read-Host ("`n[N] Create new `".csv`" file`n[M] Main menu`n[Other keys] Exit`nPlease select from above items [default = Exit]")
									Switch ($RWPA) {
										"n" {
											AutomatedMode{}
										}
										"m" {
											MainBody{}
										}
										default {
											Header
											Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
											Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
											Exit
										}
									}
								}
							}
							$Answer = Read-Host ("`n[E] Edit `".csv`" file and back to main menu`n[M] Main menu`n[Other keys] Exit`nPlease select from above items [default = Exit]")
							Switch ($Answer) {
								"e" {
									Invoke-Item $SCF
									MainBody{}
								}
								"m" {
									MainBody{}
								}
								default {
									Header
									Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
									Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
									Exit
								}
							}
					    } else {
					        Write-Host ("`nAll required data is not provided`n") -BackgroundColor Yellow -ForegroundColor DarkRed
							$Answer = Read-Host ("`nDo you want to try again (Y/N) [default = Y]")
							Switch ($Answer) {
								"n" {
									Header
									Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
									Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
									Exit
								}
								default {
									AutomatedMode{}
								}
							}
					    }
					} else {
					    Write-Host ("You have provided wrong information, number of VM(s) to be deploy should more than 0") -BackgroundColor Yellow -ForegroundColor DarkRed
					    $Answer = Read-Host ("`nDo you want to try again (Y/N) [default = Y]")
						Switch ($Answer) {
							"n" {
								Header
								Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
								Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
								Exit
							}
							default {
								AutomatedMode{}
							}
						}
					}
				}
				default {
					Header
					Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
					Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
					Exit
				}
			}
		}
	}
}

# Interactive Mode functions and process
function InteractiveMode {
	# Template Selection
	Header
	Write-Host ""
	$Templates = Get-Template | Select Name | Sort-Object Name
	if ($Templates.count -ge 2) {
		$i = 1
		$Templates | %{Write-Host $i":" $_.Name; $i++}
		$SIndex = Read-Host "Enter a number ( 1 -" $Templates.Count ")"
		$STemplate = $Templates[$SIndex - 1].Name
	} elseif ($Templates.Name -notlike "") {
		$i = 1
		$Templates | %{Write-Host $i":" $_.Name; $i++}
		$TSMC = Read-Host ("You only have one template, do you want to use it (Y/N) [default = Y]")
		Switch ($TSMC) {
			"n" {
				Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
				Exit
			}
			default {
				$STemplate = $Templates.Name
			}
		}
	} else {
		Write-Host "No template found, please check vCenter server and try again.`n" -BackgroundColor Yellow -ForegroundColor DarkRed
		Exit
	}

	# Customization Profile Selection
	Header
	Write-Host ""
	$OSCPs = Get-OSCustomizationSpec | Select Name | Sort-Object
	if ($OSCPs.count -ge 2) {
		$j = 1
		$OSCPs | %{Write-Host $j":" $_.Name; $j++}
		Write-Host $j": None"
		$OSCPRC = $OSCPs.count + 1
		$OSIndex = Read-Host "Enter a number ( 1 -" $OSCPRC ")"
		$SOSCP = $OSCPs[$OSIndex - 1].Name
		if ($OSIndex -eq $j) { $SOSCP = "None" }
	} elseif ($OSCPs.Name -notlike "") {
		$j = 1
		$OSCPs | %{Write-Host $j":" $_.Name; $j++}
		Write-Host $j": None"
		$OSIndex = Read-Host "Enter a number ( 1 - 2 )"
		Switch ($OSIndex) {
			1 { $SOSCP = $OSCPs.Name }
			2 { $SOSCP = "None" }
		}
	} else {
		Write-Host ("Currently, you don't have any customization profile available.")
		$CPSMC = Read-Host ("[C] continue the process`n[A] Abort and came back latter`nPlease select from above list [default = C]")
		Switch ($CPSMC) {
			"a" {
				Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
				Exit
			}
			default {		
				$SOSCP = "None"
			}
		}
	}

	# Host Selection
	Header
	Write-Host ""
	$VMHosts = Get-VMHost | Select Name | Sort-Object
	if ($VMHosts.count -ge 2) {
		$x = 1
		$VMHosts | %{Write-Host $x":" $_.Name; $x++}
		$VMHIndex = Read-Host "Enter a number ( 1 -" $VMHosts.Count ")"
		$SVMHost = $VMHosts[$VMHIndex - 1].Name
	} elseif ($VMHosts.Name -notlike "") {
		$x = 1
		$VMHosts | %{Write-Host $x":" $_.Name; $x++}
		$HSMC = Read-Host ("You only have one host, do you want to use it (Y/N)")
		if ($HSMC -like "y") {
			$SVMHost = $VMHosts.Name
		} elseif ($HSMC -like "n") {
			Write-Host ("`nAll process aborted by user!") -BackgroundColor Yellow -ForegroundColor DarkRed
			Read-Host ("`nPress any key to exit") -BackgroundColor Yellow -ForegroundColor DarkRed
			Exit
		}
	} else {
		Write-Host "No host found, please check vCenter server and try again."
		Read-Host ("`nPress any key to exit") -BackgroundColor Yellow -ForegroundColor DarkRed
		Exit
	}

	# Datastore Selection
	Header
	Write-Host ""
	$Datastores = Get-VMHost $SVMHost | Get-Datastore | Select Name,FreeSpaceGB,CapacityGB | Sort-Object CapacityGB
	if ($Datastores.count -ge 2) {
		$y = 1
		$Datastores | %{Write-Host $y":" $_.Name"`t`tCapacity (GB):" $_.CapacityGB"`t`tFree Space (GB):" $_.FreeSpaceGB; $y++}
		$DSIndex = Read-Host "Enter a number ( 1 -" $Datastores.count ")"
		$SDatastore = $Datastores[$DSIndex - 1].Name
	} elseif ($Datastores.Name -notlike "") {
		$y = 1
		$Datastores | %{Write-Host $y":" $_.Name"`t`tCapacity (GB):" $_.CapacityGB"`t`tFree Space (GB):" $_.FreeSpaceGB; $y++}
		$DSSMC = Read-Host ("You only have one host, do you want to use it (Y/N) [default = Y]")
		Switch ($DSSMC) {
			"n" {
				Write-Host ("`nAll process aborted by user!") -BackgroundColor Yellow -ForegroundColor DarkRed
				Exit
			}
			default {
				$SDatastore = $Datastores.Name
			}
		}
	} else {
		Write-Host "No datastore found, please check vCenter server and try again." -BackgroundColor Yellow -ForegroundColor DarkRed
		Exit
	}

	# Location Selection
	Header
	Write-Host ""
	$LSA = Read-Host "[R] Resource Pool`n[V] vApp`n[Other Keys] No Config (simple)`nPlease select location for placing new VM(s)"
	$SLocation = "Root"
	Switch ($LSA) {
		"r" {
			Write-Host ""
			$ARPs = Get-ResourcePool | Sort-Object Name
			if ($ARPs.count -ge 2) {
				$z = 1
				$ARPs | %{Write-Host $z":" $_.Name; $z++}
				$RPIndex = Read-Host "Enter a number ( 1 -" $ARPs.count ")"
				$SRP = $ARPs[$RPIndex - 1].Name
				$SLocation = $ARPs[$RPIndex - 1]
			} elseif ($ARPs.Name -notlike "") {
				$RPSMC = Read-Host ("You only have one resource pool ($ARPs.Name), do you want to use it (Y/N) [default = Y]")
				Switch ($RPSMC) {
					"n" {
						$SLocation = "Root"
					}
					default {
						$SLocation = $ARPs.Name
					}
				}
			} else {
				Write-Host ("Currently, you don't have any resource pool available.")
				$RPSMC = Read-Host ("[C] continue the process`n[A] Abort and came back latter`nPlease select from above list [default = C]")
				Switch ($RPSMC) {
					"a" {
						Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
						Exit
					}
					default {
						$SLocation = "Root"
					}
				}
			}
		}
		"v" {
			Write-Host ""
			$AVAs = Get-VApp | Sort-Object Name
			if ($AVAs.count -ge 2) {
				$k = 1
				$AVAs | %{Write-Host $k":" $_.Name;$k++}
				$VAIndex = Read-Host "Enter a number ( 1 -" $AVAs.count ")"
				$SVA = $AVAs[$VAIndex - 1].Name
				$SLocation = $AVAs[$VAIndex - 1]
				$SvApp = $AVAs[$VAIndex - 1]
			} elseif ($AVAs.Name -notlike "") {
				$VASMC = Read-Host ("You only have one resource pool ($AVAs.Name), do you want to use it (Y/N) [default = Y]")
				Switch ($VASMC) {
					"n" {
						$SLocation = "Root"
						$SvApp = "none"
					}
					default {
						$SLocation = $AVAs.Name
						$SvApp = $AVAs.Name
					}
				}
			} else {
				Write-Host ("Currently, you don't have any vApp available.")
				$VASMC = Read-Host ("[C] continue the process`n[A] Abort and came back latter`nPlease select from above list [default = C]")
				Switch ($VASMC) {
					"a" {
						Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
						Exit
					}
					default {
						$SLocation = "Root"
						$SvApp = "none"
					}
				}
			}
		}
		default {
			$SLocation = "Root"
		}
	}

	# Name Selection
	Header
	Write-Host ""
	$SName = Read-Host "Please enter VMs Naming Patern"

	# Getting VM count 
	$NVMTD = Read-Host "How many VMs do you want to deploy"

	# Getting confirmation and deploying
	Header
	Write-Host "`nNew VM(s) would be created by bellow configuration
Source Template: $STemplate
Target Host: $SVMHost
Target Datastore: $SDatastore
OS Customization Profile: $SOSCP
VM naming pattern: $SName
Number of VM(s): $NVMTD
Would place on: $SLocation"

	# Action Menu
	$NVMDConf = Read-Host "`n[C] Create VM(s)`n[S] Create and start VM(s)`n[R] Restart whole process`n[M] Main menu`n[Other Keys] Exit`nPlease select action from list [default = Exit]"
	switch ($NVMDConf) {
		"c" {
			Switch ($SOSCP) {
				"None" { $NVMs = 1..$NVMTD | foreach { New-VM -VMHost $SVMHost -Name $SName$_ -Template $STemplate -Datastore $SDatastore } }
				default { $NVMs = 1..$NVMTD | foreach { New-VM -VMHost $SVMHost -Name $SName$_ -Template $STemplate -Datastore $SDatastore -OSCustomizationSpec $SOSCP } }
			}
			Switch ($SLocation) {
				"Root" { break }
				default { $NoOut = Get-VM | Where {$_.Name -like "$SName*"} | Move-VM -Destination $SLocation }
			}
			Write-Host "`n----- Created VMs -----" -NoNewline
			Get-VM | Where {$_.Name -like "$SName*"} | Select Name,PowerState,NumCPU,MemoryMB | Format-Table -AutoSize
			Write-Host "You need to manually start your VMs.`n" -BackgroundColor Yellow -ForegroundColor Blue
			$TOS = Read-Host ("Would you like to create other series (Y/N)")
			if ($TOS -like "y") {
				MainBody{}
			} else {
				Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
				Exit
			}
		}
		"s" {
			Switch ($SOSCP) {
				"None" { $NVMs = 1..$NVMTD | foreach { New-VM -VMHost $SVMHost -Name $SName$_ -Template $STemplate -Datastore $SDatastore | Start-VM } }
				default { $NVMs = 1..$NVMTD | foreach { New-VM -VMHost $SVMHost -Name $SName$_ -Template $STemplate -Datastore $SDatastore -OSCustomizationSpec $SOSCP | Start-VM } }
			}
			Switch ($SLocation) {
				"Root" { break }
				default { $NoOut = Get-VM | Where {$_.Name -like "$SName*"} | Move-VM -Destination $SLocation }
			}
			Write-Host "`n----- Created VMs -----"
			Get-VM | Where {$_.Name -like "$SName*"} | Select Name,PowerState,NumCPU,MemoryMB | Format-Table -AutoSize
			$TOS = Read-Host ("Would you like to create other series (Y/N)")
			if ($TOS -like "y") {
				MainBody{}
			} else {
				Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
				Exit
			}
		}
		"r" {
			InteractiveMode{}
		}
		"m" {
			MainBody{}
		}
		default {
			Header
			Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
			Write-Host "Thanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
			Exit
		}
	}
}

function MainBody {
	if ($CRMB -eq "Yes") {
		Header
		$ModeSelection = Read-Host ("`n[A] Automated Mode (csv)`n[I] Interactive Mode`n[Other keys] Exit`nPlease select from above list [default = E]")
		Switch ($ModeSelection) {
			"i" {
				Header
				InteractiveMode{}
			}
			"a" {
				Header
				AutomatedMode{}
			}
			default {
				Header
				Write-Host ("`nAll process aborted by user!`n") -BackgroundColor Yellow -ForegroundColor DarkRed
				Write-Host "`nThanks for using `"Deploy Template Script (v0.4)`"`nSohrab Kasraeian Fard (@Kasraeian)`n"
				Exit
			}
		}
	} else {
		Write-Host ("Error on connecting to vCenter Server") -BackgroundColor Yellow -ForegroundColor DarkRed
	}
}

MainBody

### EOF ###

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images