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.

# 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"
$DomainAdmin = "DomainAdmin"
$OUPath = "OU=Server Computers,OU=Computers,OU=MyBusiness,DC=DOMAIN,DC=LAN"
$IPAddress = ""
$Gateway = ""
$DNS0 = ""
$DNS1 = ""

# 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