# BJDC-NEW-VM
#
# Create a new VM using a Diff VHD
#This is a sample script to create a VM using a Diff VHD.
#You could use it to setup a small lab environnement using a template VHD
#
# Author : Bruce JDC 20130312


Param(
[Parameter(Mandatory=$true,Position=0)]
[String] $vmname,
[Parameter(Position=1)]
[Int64] $vmproc = 1,
[Parameter(Position=2)]
[Int64] $vmmem = 512MB
)

import-module Hyper-V

# Default VM directories
$vmrootpath = "U:\VM\"
$vmdiskpath = $vmrootpath + "disk\"
$vmpath = $vmrootpath + "vm\"


# Create Diff Disk
$disk = Get-ChildItem -Recurse -LiteralPath $vmrootpath -Filter "*.vhd*" | Get-Vhd| where {$_.VhdType -ne "Differencing"} 
$disk | select @{name="Index";expression={[array]::IndexOf($disk,$_)}},Path | Format-Table -AutoSize
while (($tmpindex = Read-Host "Choose Disk Index") -gt ($disk.count-1)) {
    "Out of bound, choose a valid index" 
}
$vmdisk = New-VHD -Path ($vmdiskpath + $vmname+'.vhdx') -ParentPath $disk[$tmpindex].Path -Differencing 


# choose Swith
$vmswitch = Get-VMSwitch
$vmswitch |  select @{name="Index";expression={[array]::IndexOf($vmswitch,$_)}},Name,SwitchType,NetAdapterInterfaceDescription | Format-Table -AutoSize
while (($tmpindex = Read-Host "Choose Switch Index") -gt ($vmswitch.count-1)) {
    "Out of bound, choose a valid index"
}

# Create VM w/ Dynamic Memory
$vm = New-VM -Name $vmname -MemoryStartupBytes 1024MB -VHDPath $vmdisk.path -Path $vmpath -SwitchName $vmswitch[$tmpindex].name
$vm | Set-Vm -ProcessorCount $vmproc -MemoryStartupBytes $vmmem -DynamicMemory -MemoryMaximumBytes $vmmem