New-VM Template: Single VHDX File

The following PowerShell is what we use to create a new VM that will have only one VHDX file associated with it for the OS and possibly an LoB.

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
# New-VM $VMName
$VMName = "VMName"
$VMDiskSize0 = 75GB
$vSwitch = "vSwitch - Private"
$ISO = "L:\ISOs\WinServ19B-2018-10-09.ISO"
$AutoMaticStartDelay = "90"

# Create the VM
New-VHD -Path "L:\Hyper-V\Virtual Hard Disks\$($VMName)_D0.VHDX" -Dynamic -SizeBytes $VMDiskSize0
New-VM -Name $VMName -Generation 2 -Memory 8GB –SwitchName "$vSwitch"
Set-VMProcessor $VMName -Count 2
Add-VMHardDiskDrive -VMName $VMName -Path "L:\Hyper-V\Virtual Hard Disks\$($VMName)_D0.VHDX"
Add-VMDvdDrive -VMName $VMName -ControllerNumber 0 -ControllerLocation 63
Set-VMDvdDrive -VMName $VMName –Path $ISO
Set-VM –Name $VMName –AutomaticStartAction Start -AutomaticStartDelay 120 -AutomaticStopAction ShutDown

# Remove .ISOs from all VMs
Set-VMDvdDrive -VMName * –Path ""

# Variables
$Domain = "DOMAIN.Com"
$NETBIOS = "DOMAIN"
$DomainAdmin = "DomainAdmin"
$OUPath = "OU=Server Computers,OU=Computers,OU=MyBusiness,DC=DOMAIN,DC=LAN"
$IPAddress = "192.168.99.240"
$Gateway = "192.168.99.1"
$DNS0 = "192.168.99.254"
$DNS1 = "192.168.99.252"

# PowerShell Remote Access via Host elevated PowerShell
Enter-PSSession -VMName $VMName -Credential $VMName\Administrator
Enter-PSSession -VMName $VMName -Credential $NetBIOS\Administrator
Enter-PSSession -VMName $VMName -Credential $NetBIOS\$DomainAdmin

# Post rename join domain
Add-Computer -Domain $Domain -Credential $NETBIOS\$DomainAdmin -OUPath $OUPath -Restart

# Set Static IP Address for the VM
Set-NetIPInterface -InterfaceAlias Ethernet -DHCP Disabled
Remove-NetIPAddress -InterfaceAlias Ethernet -Confirm:$false
New-NetIPAddress -InterfaceAlias Ethernet -IPAddress $IPAddress –DefaultGateway $Gateway -PrefixLength 24
Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses $DNS0,$DNS1
IPConfig /RegisterDNS

# Format the second partition
Get-Disk | Where-Object {$_.OperationalStatus -eq "offline"} | Set-Disk -isoffline $False
Get-Disk | Where-Object {$_.PartitionStyle -eq "RAW"} | Initialize-Disk -PartitionStyle "GPT" -PassThru
Get-Disk | Where-Object {$_.Size -gt 101GB} | New-Partition -UseMaximumSize -DriveLetter L | Format-Volume -Confirm:$false -FileSystem NTFS -NewFileSystemLabel "WorkingStorage" -AllocationUnitSize 65536 -force