PowerShell script utilizes “Using” scope modifier to create VM from existing .vhdx file.

The following interactive PowerShell 3.0 script creates a new virtual machine. It utilizes the ‘Using’ scope modifier to pass local variables to remote machines with the invoke-command cmdlet.

An existing .vhdx file is copied to a new location and renamed . Same file is used to create the virtual machine. The script assumes the VM Path and Switch have already been setup on any Windows Server 2012 Hyper-V host .

function New-VirtualMachine {
Param ($vmname = (Read-Host "Enter VMName"),
[int]$memorystartupbytes = (Read-Host "Enter StartupMemory (Press Enter to Choose 1000MB)"),
$switchname =(Read-Host " Enter Switchname"),
$computername = (Read-Host " Enter Hyperv Host Name"),
$destination = "c:\Hyperv\",
$templatefolder = "c:\vhdtemplates\" ,
$vhdfiles = (Invoke-Command -ComputerName $computername -ScriptBlock {Get-ChildItem -Path $using:templatefolder -File | ft Name | Out-String}) ,
$listvhdfiles = (Write-Host -Object $vhdfiles) ,
$templatefile = (Read-Host " Select Template File From .VHDX List")

)
if ($memorystartupbytes -eq ""){$memorystartupbytes=1000MB} ; if ($memorystartupbytes -eq $NULL){$memorystartupbytes=1000MB}
Invoke-Command -ComputerName $computername -ScriptBlock {Copy-Item -Path ("$using:templatefolder" + "$using:templatefile") -Destination $using:destination -Verbose}
Invoke-Command -ComputerName $computername -ScriptBlock {Rename-Item -Path ($using:destination + $using:templatefile) -NewName ($using:vmname +".vhdx") -Force -Verbose }
New-VM -Name $vmname -VHDPath ("$destination" + "$vmname" + ".vhdx") -MemoryStartupBytes $memorystartupbytes -SwitchName $switchname -ComputerName $computername -Verbose

}
New-VirtualMachine

More information about the “Using” scope modifier can be found in PowerShell help with: Get-Help about_Remote_Variables -Full .

Advertisement
This entry was posted in PowerShell, PowerShell 3.0, Windows Server 2012, Windows Server 2012 R2 and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s