Does anyone have a complete example of how to create a VM that has custom settings and VHD's attached using WMI from PowerShell? (need to use WMI and not the library from codeplex) I have found a lot of partial scripts that create default vm's without vhd's attached and a lot of broken links pointing to solutions. Have also seen reference that it can be done with AddVirtualSystemResources but have not seen any examples. Here is what I have so far, and thanks in advance!
Create VM with no VHD's, and create VHD but don't know how to connect the VHD or create it during the VM creation steps:
#get the current computer name
$currentname=get-wmiobject Win32_ComputerSystem
$namespace=$currentname.name
#create a VHD
$disk = Get-WmiObject Msvm_ImageManagementService -namespace "root\virtualization" -computername $namespace
$disk.CreateDynamicVirtualHardDisk("$env:systemdrive\nameofvhd.vhd", 20000000000)|out-null
$newvm="Test"
$description="This is the Description"
$path="$env:systemdrive\testvmfolder"
# Create a VM
# Get a new instance of Msvm_VirtualSystemGlobalSettingData
$vsgsdClass = [wmiclass]"root\virtualization:Msvm_VirtualSystemGlobalSettingData"
$vsgsd = $vsgsdClass.CreateInstance()
$vsgsd.ElementName = $newvm
$vsgsd.Description = $description
$vsgsd.ExternalDataRoot = $path
# Get the managment service and define the system from the embedded instance
$vmms = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService
$result = $vmms.DefineVirtualSystem($vsgsd.GetText(1))
if($result.ReturnValue -eq 4096){
# A Job was started, and can be tracked using its Msvm_Job instance
$job = [wmi]$result.Job
# Wait for job to finish
while($job.jobstate -lt 7){$job.get()}
# Return the Job's error code
return $job.ErrorCode
}
# Otherwise, the method completed
return $result.ReturnValue