public void CreateVM(VMInitObject vm) { Console.WriteLine("CreateVM " + vm.Name); if (!string.IsNullOrEmpty(vm.IPAddress) && string.IsNullOrEmpty(vm.MacAddress)) { throw new InvalidOperationException("MAC address must be specified"); } if (GetVMs(vm.Name).Any()) { throw new InvalidOperationException("A virtual machine with that name already exists."); } string path = null; try { path = string.Format("{0}{1}.vhdx", MachineFolder, vm.Name); File.Copy(ImagesFolder + vm.ImageName, path); var cmd = CreateCommand("New-VM", vm.Name); cmd.Parameters.Add("MemoryStartupBytes", vm.Memory); cmd.Parameters.Add("VHDPath", Path.Combine(MachineFolderLocal, $"{vm.Name}.vhdx")); ExecuteCommand(cmd); Thread.Sleep(2000); if (!string.IsNullOrEmpty(vm.MacAddress)) { cmd = CreateCommand("Set-VMNetworkAdapter"); cmd.Parameters.Add("VMName", vm.Name); cmd.Parameters.Add("StaticMacAddress", vm.MacAddress); ExecuteCommand(cmd); } Thread.Sleep(1000); cmd = CreateCommand("Connect-VMNetworkAdapter"); cmd.Parameters.Add("VMName", vm.Name); cmd.Parameters.Add("SwitchName", NetworkName); ExecuteCommand(cmd); if (!string.IsNullOrEmpty(vm.IPAddress)) { cmd = new Command("Add-DhcpServerv4Reservation"); cmd.Parameters.Add("ScopeId", DHCPScope); cmd.Parameters.Add("IPAddress", vm.IPAddress); cmd.Parameters.Add("ClientId", vm.MacAddress); cmd.Parameters.Add("Name", vm.Name); ExecuteCommand(cmd); } } catch (Exception ex) { if (File.Exists(path)) { try { var cmd = CreateCommand("Remove-VM", vm.Name); cmd.Parameters.Add("Force"); ExecuteCommand(cmd); } catch { } File.Delete(path); } Logger.Log("NewVM", ex.ToString()); throw; } }
public bool CreateVM(VMInitObject vm) { Connector.CreateVM(vm); return(true); }