Tuesday 19 January 2016

Powershell script for creating New-VM

Hi Folks,
I have just enabled hyper-v role on my test server. Thought of writing a powershell script which creates VM based on some input's by user.

Below is a small script which creates Hyper-V VM. It asks for basic VM parameters from the user.




<# Creating Virtual Machine in Hyper-v using powershell#>




<#Check if a switch is already created#>
 
 
$switch = Read-host 'Please enter an Existing switch Name'

$existingswitch = Get-VMSwitch

if ($existingswitch)

{ if($existingswitch.name -contains $switch)

{$switchname = $switch}

else{$switchname = 'testswitch'}



}
 
else{

$switch = Read-Host 'Please enter New switch name'

New-vmswitch -name $switch -SwitchType Internal

$switchname = $switch



}
 
$VMName = Read-Host 'Please enter the VM Name'

$RAMsize = Read-Host 'Please enter the RAM Size:'

$Imagepath = Read-Host 'Please enter image path'

$HDpath = Read-host 'Please enter VHD path(ADD .vhdx):'

$HDSize = Read-Host 'Plese enter HD size(ADD GB):'

$ExistingVM = Get-VM

if ($ExistingVM.name -contains $VMName)

{ write-host "VM Name already exists"}

Else {

New-VM $VMName -BootDevice CD -SwitchName $switchname }

Set-VMMemory -VMname $VMName -StartupBytes (Invoke-Expression $RAMsize)

Set-VMProcessor -vm $VMName -Count 1

New-VHD -Path $HDpath -Dynamic -SizeBytes (Invoke-Expression $HDSize)

Add-VMHardDiskDrive -vmname $VMName -ControllerType IDE -ControllerNumber 0 -Path $HDpath

Set-VMDvdDrive -VMName $VMName -ControllerLocation 0 -ControllerNumber 1 -Path $Imagepath

$bootup = Get-VMBios -VMName $VMName | Select-Object -Property StartupOrder




if
 
 
($bootup.StartupOrder[0] -notcontains 'CD')



{
 
Set-VMBios -vmname $VMName -StartupOrder @("CD", "IDE", "LegacyNetworkAdapter", "Floppy")



}
 
else
 
 
{
 
Start-VM -Name $VMName



}
 
 

Thursday 24 December 2015