Example #1
0
        // Alias: Stop-VM
        public static void StopVm(string ComputerName, string Name, bool PowerOff, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;
            string Flag = PowerOff ? "-PowerOff" : "";

            PSWrapper.Execute(ComputerName, $"Stop-VM -Name \"{Name}\" {Flag} -Force", out res, handlers);
        }
Example #2
0
        // Alias: Get-VM
        public static List <PSObject> GetPsVm(string ComputerName)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, "Get-VM", out res);
            return(res.ToList());
        }
Example #3
0
        public static void NewTemplate(string hostName, string name, Guid baseUid, string switchName, JToken config, PsStreamEventHandlers handlers = null)
        {
            var    baseVm  = SessionManager.GetDatabase().GetVm(baseUid);
            var    srcHost = baseVm.Host;
            var    dstHost = hostName;
            string dstDir  = Path.Combine(Settings.Default.vhdPath, srcHost);
            string srcPath = GetTopMostParent(baseVm.Host, baseVm.VhdPath[0]);
            string dstPath = Path.Combine(dstDir, baseUid.ToString() + ".vhdx");
            string vhdPath = Path.Combine(Settings.Default.vhdPath, name + ".vhdx");

            if (srcHost != hostName)
            {
                if (!PathExists(dstHost, dstPath))
                {
                    NewDirectory(dstHost, dstDir, handlers);
                    CopyFile(srcHost, dstHost, srcPath, dstPath, handlers);
                }
            }
            else
            {
                dstPath = srcPath;
            }
            HyperV.NewVHD(dstHost, dstPath, vhdPath, handlers);
            PSWrapper.Execute(dstHost, config, handlers, name, vhdPath, switchName);

            var vm = HyperV.GetVm(hostName, name, handlers).GetDbObject();

            vm.ParentHost = srcHost;
            vm.ParentUuid = baseUid;
            vm.VmType     = (int)VirtualMachineType.TEMPLATE;
            SessionManager.GetDatabase().SetVm(vm);
        }
Example #4
0
        // Alias: Get-VMSwitch
        public static List <PSObject> GetVmSwitch(string ComputerName)
        {
            Collection <PSObject> res;

            PSWrapper.FastExecute(ComputerName, "Get-VMSwitch", out res);
            return(res.ToList());
        }
Example #5
0
        public static void newvmswitch(string[] tokens)
        {
            string server = Dns.GetHostName();

            if (tokens.Length == 2)
            {
                server = tokens[1];
            }
            Console.Write("Name: ");
            string name = Console.ReadLine();

            Console.WriteLine("Choose an adapter:");
            var adapters = NetAdapter.GetNetAdapter(server);

            for (int i = 0; i < adapters.Count; i++)
            {
                Console.WriteLine($"[{i}] ({ adapters[i].Members["Name"].Value }) { adapters[i].Members["InterfaceDescription"].Value }");
            }
            var ada = adapters[GetSelectedIndex()].Members["InterfaceDescription"].Value.ToString();

            PSWrapper.Execute(server, (ps) => {
                return(ps.AddCommand("New-VMSwitch")
                       .AddParameter("Name", name)
                       .AddParameter("NetAdapterInterfaceDescription", ada)
                       .AddParameter("AllowManagementOS", true)
                       .Invoke());
            }, PsStreamEventHandlers.DefaultHandlers);
        }
Example #6
0
 public static bool PathExists(string host, string path, PsStreamEventHandlers handlers = null)
 {
     return((bool)PSWrapper.Execute(host, (ps) =>
     {
         ps.AddCommand("Test-Path").AddParameter("path", path);
         return ps.Invoke();
     })[0].BaseObject);
 }
Example #7
0
 // Alias: New-VHD
 public static PSObject NewVHD(string ComputerName, string ParentPath, string Path, PsStreamEventHandlers handlers = null)
 {
     return(PSWrapper.Execute(ComputerName, (ps) =>
     {
         ps.AddStatement().AddScript($"New-VHD -ParentPath \"{ParentPath}\" -Path \"{Path}\" -Differencing");
         return ps.Invoke();
     }, handlers)[0]);
 }
Example #8
0
        // Alias: Get-NetAdapter -Physical
        public static List <PSObject> GetNetAdapter(string ComputerName)
        {
            List <PSObject> res = new List <PSObject>();

            res.AddRange(PSWrapper.Execute(ComputerName, (ps) =>
                                           ps.AddStatement().AddCommand("Get-NetAdapter").AddParameter("Physical").Invoke()));
            return(res);
        }
Example #9
0
 // Alias: Set-VHD
 public static void SetVHD(string ComputerName, string ParentPath, string Path, bool IgnoreMismatchId, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(ComputerName, (ps) =>
     {
         string Flag = /*IgnoreMismatchId ? "-IgnoreMismatchId" :*/ "";
         ps.AddStatement().AddScript($"Set-VHD -Path \"{Path}\" -ParentPath \"{ParentPath}\" {Flag}");
         return(ps.Invoke());
     }, handlers);
 }
Example #10
0
        // Alias: Get-VHD
        public static List <PSObject> GetVhd(string ComputerName, string Path, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            res = PSWrapper.FastExecute(ComputerName, (ps) =>
            {
                return(ps.AddCommand("Get-VHD").AddParameter("Path", Path).Invoke());
            }, handlers);
            return(res.ToList());
        }
Example #11
0
 public static void NewDirectory(string host, string path, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(host, (ps) =>
     {
         return(ps.AddCommand("New-Item")
                .AddParameter("Type", "Directory")
                .AddParameter("Path", path)
                .AddParameter("Force").Invoke());
     }, handlers);
 }
Example #12
0
 // Alias: New-VM
 public static PSObject NewVm(string ComputerName, Dictionary <string, object> Parameters)
 {
     return(PSWrapper.Execute(ComputerName, (ps) =>
     {
         ps.AddStatement().AddCommand("New-VM")
         .AddParameters(Parameters)
         .AddParameter("Force");
         return ps.Invoke();
     })[0]);
 }
Example #13
0
 public static void CopyFile(string srcHost, string dstHost, string src, string dst, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(dstHost, (ps) =>
     {
         ps.AddCommand("Set-Variable").AddParameter("Name", "cred").AddParameter("Value", SessionManager.GetCredential());
         ps.AddScript($"Copy-Item \"{src}\" \"{dst}\" -Force –FromSession (New-PSSession –ComputerName {srcHost} -Credential $cred)");
         ps.Invoke();
         return(null);
     }, handlers);
 }
Example #14
0
        public static string[] GetChildItems(string host, string path, string filter = null)
        {
            Collection <PSObject> res = null;

            PSWrapper.Execute(host, $"Get-ChildItem -Path \"{path}\" -Filter \"{filter}\" -File -Recurse", out res);
            if (res == null || res.Count <= 0)
            {
                return(null);
            }
            return(res.ToList().Select(p => p.Members["FullName"].Value.ToString()).ToArray());
        }
Example #15
0
        // Alias: Get-VMHost
        public static PSObject GetVmHost(string ComputerName, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Get-VMHost -ComputerName \"{ComputerName}\"", out res, handlers);
            if (res == null || res.Count <= 0)
            {
                return(null);
            }
            return(res[0]);
        }
Example #16
0
        // Alias: Get-VM
        /// <exception cref="Exception">May throw exceptions</exception>
        public static VirtualMachine GetVm(string hostName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> objs = null;

            PSWrapper.FastExecute(hostName, $"Get-Vm -Name \"{Name}\"", out objs, handlers);
            if (objs == null || objs.Count == 0)
            {
                return(null);
            }
            return(VirtualMachine.FromPSObject(objs[0], hostName));
        }
Example #17
0
        public static void NewDeployment(string hostName, string name, Guid tmplUid, string switchName, JToken config, PsStreamEventHandlers handlers = null)
        {
            var tmplVm = SessionManager.GetDatabase().GetVm(tmplUid);
            var baseVm = SessionManager.GetDatabase().GetVm(tmplVm.ParentUuid);

            if (baseVm == null)
            {
                throw new Exception("Template VM without parent.");
            }

            var    bsrcHost = baseVm.Host;
            string bdstDir  = Path.Combine(Settings.Default.vhdPath, bsrcHost);
            string bdstPath = Path.Combine(bdstDir, baseVm.Uuid.ToString() + ".vhdx");
            string bsrcPath = GetTopMostParent(baseVm.Host, baseVm.VhdPath[0]);

            var    tsrcHost = tmplVm.Host;
            string tsrcPath = tmplVm.VhdPath[0];
            string dstHost  = hostName;
            string vhdPath  = Path.Combine(Settings.Default.vhdPath, name + ".vhdx");

            if (bsrcHost != hostName)
            {
                if (!PathExists(dstHost, bdstPath))
                {
                    NewDirectory(dstHost, bdstDir, handlers);
                    CopyFile(bsrcHost, dstHost, bsrcPath, bdstPath, handlers);
                }
            }
            else
            {
                bdstPath = bsrcPath;
            }

            if (!PathExists(dstHost, vhdPath))
            {
                NewDirectory(dstHost, bdstDir, handlers);
                CopyFile(tsrcHost, dstHost, tsrcPath, vhdPath, handlers);
            }
            HyperV.SetVHD(dstHost, bdstPath, vhdPath, true, handlers);
            PSWrapper.Execute(dstHost, config, handlers, name, vhdPath, switchName);

            var vm = HyperV.GetVm(hostName, name, handlers).GetDbObject();

            vm.ParentHost = bsrcHost;
            vm.ParentUuid = baseVm.Uuid;
            vm.VmType     = (int)VirtualMachineType.DEPLOY;
            SessionManager.GetDatabase().SetVm(vm);
        }
Example #18
0
        // Alias: Get-VM
        /// <exception cref="Exception">May throw exceptions</exception>
        public static List <VirtualMachine> GetVm(string hostName, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> objs = null;

            PSWrapper.FastExecute(hostName, "Get-Vm", out objs, handlers);
            if (objs == null || objs.Count == 0)
            {
                return(new List <VirtualMachine>());
            }
            List <VirtualMachine> machines = new List <VirtualMachine>();

            foreach (var m in objs)
            {
                machines.Add(VirtualMachine.FromPSObject(m, hostName));
            }
            return(machines);
        }
Example #19
0
 public static VirtualMachine FromPSObject(PSObject m, string hostName)
 {
     return(new VirtualMachine
     {
         Host = hostName,
         Name = m.Members["VMName"].Value.ToString(),
         Uuid = (Guid)m.Members["VMId"].Value,
         State = VirtualMachine.GetStateFromString(m.Members["State"].Value.ToString()),
         VhdPath = Array.ConvertAll(PSWrapper.Execute(hostName, (ps) =>
         {
             return ps.AddCommand("Get-VM")
             .AddParameter("Id", m.Members["VMId"].Value)
             .AddCommand("Get-VMHardDiskDrive")
             .Invoke();
         }).ToArray(), (x) => { return x.Members["Path"].Value.ToString(); }),
         Type = VirtualMachineType.NONE
     });
 }
Example #20
0
        public static void newvm(string[] tokens)
        {
            // Get user input
            string server = Dns.GetHostName();

            if (tokens.Length == 2)
            {
                server = tokens[1];
            }
            string name, vhdpath, vmswitch;

            Console.Write("Name: ");
            name = Console.ReadLine();
            Console.WriteLine($@"Default VHD Path is: C:\VHDs\{name}.vhdx");
            Console.Write("VHD Name (leave blank for default): ");
            vhdpath = Console.ReadLine();
            if (string.IsNullOrEmpty(vhdpath))
            {
                vhdpath = name;
            }
            Console.WriteLine("Available switches:");
            var switches = HyperV.GetVmSwitch(server);

            for (int i = 0; i < switches.Count; i++)
            {
                Console.WriteLine($"[{i}] { switches[i].Members["Name"].Value }");
            }
            vmswitch = switches[GetSelectedIndex()].Members["Name"].Value.ToString();

            // Parse JSON
            using (StreamReader reader = File.OpenText(@"Config\templates.json"))
            {
                JObject doc = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
                Console.WriteLine("All available VM configurations:");
                for (int i = 0; i < doc["templates"].Count(); i++)
                {
                    Console.WriteLine($"[{ i }] { doc["templates"][i]["name"] }");
                }
                var config = doc["templates"][GetSelectedIndex()];
                PSWrapper.Execute(server, config, PsStreamEventHandlers.DefaultHandlers, name, vhdpath, vmswitch);
            }
        }
Example #21
0
        public static void StartService(string host, string svc, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res = null;

            PSWrapper.Execute(host, $"net start \"{svc}\" | Write-Verbose -Verbose", out res, handlers);
        }
Example #22
0
        // Alias: Remove-VMSnapshot
        public static void RemoveVmSnapshot(string ComputerName, string VMName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Remove-VMSnapshot -Name \"{Name}\" -VMName \"{VMName}\" -IncludeAllChildSnapshots -Confirm:$false", out res, handlers);
        }
Example #23
0
 /// <exception cref="Exception">May throw exceptions</exception>
 public static void RestartService(string hostName, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(hostName, (ps) => ps.AddCommand("Restart-Service").AddParameter("Name", "vmms").Invoke(), handlers);
 }
Example #24
0
        public static void DeleteItem(string host, string path)
        {
            Collection <PSObject> res = null;

            PSWrapper.FastExecute(host, $"Remove-Item –Path \"{path}\"", out res);
        }
Example #25
0
        // Alias: Checkpoint-VM
        public static void CheckpointVm(string ComputerName, string VMName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Checkpoint-VM -SnapshotName \"{Name}\" -Name \"{VMName}\" -Confirm:$false", out res, handlers);
        }
Example #26
0
        // Alias: Save-VM
        public static void SaveVm(string ComputerName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Save-VM -Name \"{Name}\"", out res, handlers);
        }