Home A PowerShell script to create many new VMware VMs
Post
Cancel

A PowerShell script to create many new VMware VMs

This script will create one or more inventory items aka a virtual machines using PowerShell. It connects an ISO image and defines all of the hardware. It does not install the OS.

This script requires a file in the same folder as the script called “machines.txt”. Just list each machine on it’s own line. The “name” is the vCenter name not the hostname.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
$ErrorActionPreference = "Stop"

$vCenter = "192.168.1.89"  # IP or FQDN of vCenter
$vCUser = "administrator@vsphere.local"
$vCPW = "password"
$Host_name = "192.168.1.93"  # IP or FQDN of the host to put the VM on
#$VM_name = "AdamsVM"
$Date = Get-Date
$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$NotesString = "Created on $Date by $CurrentUser"
$DS_name = "3TB1"
$VM_DiskGB = "32"
$VM_MemoryGB = 4
$VM_NumCPU = 1 # Sockets
$VM_CoresPerSocket = 2 # Cores per socket


Write-Host "Connecting to vCenter" -ForeGroundColor "Green"
Connect-VIServer -Server $vCenter -User $vCUser -Password $vCPW -Force | Out-Null
Write-Host " Connected to vCenter" -ForeGroundColor "Green"

$VMHost = Get-VMHost -Name $Host_name

# -------------------------------------------------------------------------
foreach($VM_name in [System.IO.File]::ReadLines("$PSScriptRoot\machines.txt"))
{
  Write-Host "  Creating the VM $VM_name ..." -ForeGroundColor "Green"

  New-VM -Name $VM_name -ResourcePool $VMHost `
  -Datastore $DS_name -NumCPU $VM_CoresPerSocket -CoresPerSocket $VM_CoresPerSocket `
  -MemoryGB $VM_MemoryGB -DiskGB $VM_DiskGB `
  -NetworkName "VM Network" -DiskStorageFormat Thin -Notes "$NotesString" `
  -CpuHotAddEnabled 1 -CpuHotRemoveEnabled 1 -MemoryHotAddEnabled 1 `
  -GuestId ubuntu64Guest `
  | Out-Null

  Write-Host "   VM Created" -ForeGroundColor "Green"

  Write-Host "  Attaching the CD ISO..." -ForeGroundColor "Green"

  New-CDDrive -VM $VM_name -ISOPath "[3TB1] ubuntu-22.04-live-server-amd64.iso" `
  -StartConnected | Out-Null

  Write-Host "   CD attached" -ForeGroundColor "Green"
}
# -------------------------------------------------------------------------


Write-Host "Disconnecting from vCenter" -ForeGroundColor "Green"
Disconnect-VIServer -Server $vCenter -Force -Confirm:$false
Write-Host " Disconnected from vCenter" -ForeGroundColor "Green"

Write-Host "All done." -ForeGroundColor "Green"
This post is licensed under CC BY 4.0 by the author.