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
.