Skip to content

Instantly share code, notes, and snippets.

@tomfanning
Created January 11, 2016 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfanning/13b988f57af6f088ca9e to your computer and use it in GitHub Desktop.
Save tomfanning/13b988f57af6f088ca9e to your computer and use it in GitHub Desktop.
Create a blank Hyper-V VM in the correct location
$ErrorActionPreference="Stop"
$vmname = read-host 'What name should the new VM have?'
$destdrive = read-host 'What drive should the new VM live on?'
$sourcevhdx = read-host 'What is the full path to the source VHDX? (enter for blank)'
$lan = read-host 'What virtual switch (name) should the VM be connected to? (enter for default)'
$destpath = $destdrive + ':\HyperV'
$vmrootpath = join-path $destpath $vmname
if (test-path -path $vmrootpath) {
$yn = read-host "Export directory $vmrootpath exists - remove? y/n"
if ($yn -eq "y") {
write-host "Removing $vmrootpath"
remove-item -recurse $vmrootpath
} else {
write-host "Exiting"
exit
}
}
new-vm -name $vmname -memorystartupbytes 4096mb -generation 2
set-vmprocessor $vmname -count 2
export-vm -name $vmname -path $destpath
remove-vm -name $vmname -force
$configpath = join-path $vmrootpath "Virtual Machines"
$vhdpath = join-path $vmrootpath "Virtual Hard Disks"
import-vm -path (get-childitem $configpath -file).fullname
$vhdx = join-path $vhdpath ($vmname + '.vhdx')
if ($sourcevhdx) {
write-host Copying source VHDX to $vhdx
copy-item $sourcevhdx $vhdx
} else {
write-host "Creating blank 20GB dynamic VHDX at $vhdx"
new-vhd -path $vhdx -sizebytes 20GB
}
Add-VMHardDiskDrive -vmname $vmname -controllertype scsi -path $vhdx
set-vmfirmware -vmname $vmname -bootorder (Get-VMHardDiskDrive -vmname $vmname)
if ($lan) {
Connect-VMNetworkAdapter -VMName $vmname -switchname $lan
} else {
$sw = Get-VMSwitch | select-object -first 1
$sw | Connect-VMNetworkAdapter -VMName $vmname
}
write-host All done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment