New-VM Template: Dual VHDX Files

The following PowerShell is what we use to create a new VM that will have two VHDX files associated with it. One for the guest OS and the second for LoB related content such as shared files and folders or database content.

# New-VM $VMName
$VMName = "VMName"
$VMDiskSize0 = 75GB
$VMDiskSize1 = 150GB
$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-VHD -Path "L:\Hyper-V\Virtual Hard Disks\$($VMName)_D1.VHDX" -Dynamic -SizeBytes $VMDiskSize1
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-VMHardDiskDrive -VMName $VMName -Path "L:\Hyper-V\Virtual Hard Disks\$($VMName)_D1.VHDX"
Add-VMDvdDrive -VMName $VMName -ControllerNumber 0 -ControllerLocation 63
Set-VMDvdDrive -VMName $VMName –Path $ISO
Set-VM –Name $VMName –AutomaticStartAction Start -AutomaticStartDelay $AutoMaticStartDelay -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=Local"
$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

# Rename Computer (don't forget to paste the variable into PSSession)
Rename-Computer -NewName $VMNAme -Restart

# 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