Create A Windows Server 2012 R2 Hyper-V Machine with PowerShell

Creating a new guest hyper-v image using the Hyper-V Manager can become tedious after awhile especially when the need arises for creating an entire lab environment consisting of multiple guests all in one shot.

Using PowerShell to accomplish a task like this is the answer.  What follows is a very simple example that can be used to create more elaborate solutions toward that goal.  The intent is to demonstrate some of the basics while leaving the more elaborate solution (parameters, multiple guests, etc.) as an exercise for the reader.

NOTE:  Since the title of this article is Windows Server 2012 R2, this is not intended to function on Windows Server 2012.

This example creates a dual (2) CPU, 2GB RAM, guest with drive C: and a second drive (in this case a DC for storage of SYSVOL and NTDS), sets up the DVD drive with an .iso for installation of the OS, uses the default Network Adapter and creates a second for private use.

 

# Create the Virtual Machine

New-VM -Name RonBokDC01 -MemoryStartupBytes 2048MB -Path D:\HyperV\RonBokDC01 -Generation 2

 

# Create the Virtual Machines Required Disks

New-VHD -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\RonBokDC01.vhdx’ -SizeBytes 127GB -Dynamic

New-VHD -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\Data.vhdx’ -SizeBytes 127GB -Dynamic

 

# Attach the Virtual Machines Disks to the SCSI Controller

Add-VMHardDiskDrive -VMName RonBokDC01 -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\RonBokDC01.vhdx’ -ControllerType SCSI -ControllerNumber 0 -ControllerLocation 0

Add-VMHardDiskDrive -VMName RonBokDC01 -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\Data.vhdx’ -ControllerType SCSI -ControllerNumber 0 -ControllerLocation 1

 

# Attach the Windows Server 2012 R2 .iso to the DVD for installation.

Set-VMDvdDrive -VMName RonBokDC01 -ControllerNumber 1 -Path ‘E:\Downloads\MSDN\Operating Systems\en_windows_server_2012_r2_x64_dvd_2707946.iso’

 

#Get the first Network Adapter, usally named ‘Network Adapter’ and attach it to the Public NIC of the VM Host.

$NetAdapter = Get-VMNetworkAdapter -VMName RonBokDC01

$NetAdapterName = $NetAdapter.Name

Connect-VMNetworkAdapter -VMName RonBokDC01 -Name $NetAdapterName -SwitchName ‘Intel(R) 82574L Gigabit Network Connection – Virtual Switch’

 

#Rename the first Network Adapter to Public.

Rename-VMNetworkAdapter -VMName RonBokDC01 -Name $NetAdapterName -NewName ‘Public’

 

#Add another Network Adapter called Private and attach it to the Private Network Switch.

Add-VMNetworkAdapter -VMName RonBokDC01 -Name ‘Private’ -IsLegacy $false -SwitchName ‘Private’

 

#Set Processors

Set-VMProcessor -VMName RonBokDC01 -Count 2

 

Tagged with: , ,
Posted in Hyper-V, PowerShell, Windows Server 2012 R2

Leave a comment