IsAvailable(
            string serverName,
            string vmName)
        {
            ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
            {
                UInt16 enhancedModeState = (UInt16)vm.GetPropertyValue("EnhancedSessionModeState");

                if (enhancedModeState == CimEnabledStateEnabled)
                {
                    Console.WriteLine("Enhanced mode is allowed and currently available on VM {0} on server {1}", vmName, serverName);
                }
                else if (enhancedModeState == CimEnabledStateDisabled)
                {
                    Console.WriteLine("Enhanced mode is not allowed on VM {0} on server {1}", vmName, serverName);
                }
                else if (enhancedModeState == CimEnabledStateEnabledButOffline)
                {
                    Console.WriteLine("Enhanced mode is allowed and but not currently available on VM {0} on server {1}", vmName, serverName);
                }
                else
                {
                    Console.WriteLine("Enhanced mode state on VM {0} on server {1} is {2}", vmName, serverName, enhancedModeState);
                }
            }
        }
        RemoveReplicationRelationshipEx(
            string name,
            UInt16 relationshipType)
        {
            if (relationshipType > 1)
            {
                throw new ArgumentException("Replication relationship should be either 0 or 1");
            }

            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the Msvm_ComputerSystem.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
            {
                string vmPath = vm.Path.Path;

                //
                // Retrieve the specified Msvm_ReplicationRelationship object.
                //
                using (ManagementObject replicationRelationship =
                           ReplicaUtilities.GetReplicationRelationshipObject(vm, relationshipType))
                {
                    if (replicationRelationship == null)
                    {
                        throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                                    "No Msvm_ReplicationRelationship object with relationship type {0} could be found",
                                                                    relationshipType));
                    }

                    string replicationRelationshipEmbedded =
                        replicationRelationship.GetText(TextFormat.WmiDtd20);

                    using (ManagementObject replicationService =
                               ReplicaUtilities.GetVirtualMachineReplicationService(scope))
                    {
                        using (ManagementBaseObject inParams =
                                   replicationService.GetMethodParameters("RemoveReplicationRelationshipEx"))
                        {
                            inParams["ComputerSystem"]          = vmPath;
                            inParams["ReplicationRelationship"] = replicationRelationshipEmbedded;

                            using (ManagementBaseObject outParams =
                                       replicationService.InvokeMethod("RemoveReplicationRelationshipEx",
                                                                       inParams,
                                                                       null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                    }
                }

                Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                "{0} replication is successfully removed for virtual machine \"{1}\"",
                                                relationshipType == 0 ? "Primary" : "Extended",
                                                name));
            }
        }
Exemple #3
0
        GetResourcePoolPath(
            ManagementScope scope,
            string poolId
            )
        {
            string poolQuery =
                "SELECT * FROM Msvm_ResourcePool WHERE ResourceType = " + FcConnectionResourceType;

            if (poolId == null || poolId.Length == 0)
            {
                poolQuery += " AND Primordial = TRUE";
            }
            else
            {
                poolQuery += " AND PoolId = '" + poolId + "'";
            }

            ObjectQuery query = new ObjectQuery(poolQuery);

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
                using (ManagementObjectCollection pools = searcher.Get())
                {
                    return(WmiUtilities.GetFirstObjectFromCollection(pools).Path.Path);
                }
        }
        DisplayPoolVerbose(
            string resourceDisplayName,
            string poolId)
        {
            Console.WriteLine(
                "Displaying the Msvm_ResourcePool, Msvm_ResourcePoolSettingData and " +
                "the Msvm_ResourceAllocationSettingsData properties for the following " +
                "resource pool:\n");

            ManagementScope scope = ResourcePoolUtilities.GetManagementScope();

            using (ManagementObject pool = WmiUtilities.GetResourcePool(
                       ResourceUtilities.GetResourceType(resourceDisplayName),
                       ResourceUtilities.GetResourceSubType(resourceDisplayName),
                       poolId,
                       scope))
            {
                DisplayResourcePool(pool);

                MsvmResourceAllocationSettingData.DisplayPoolResourceAllocationSettingData(
                    scope,
                    pool);

                MsvmResourcePoolSettingData.DisplayPoolResourcePoolSettingData(
                    scope,
                    pool);
            }
        }
        public bool PowerOff()
        {
            bool result = false;

            using (ManagementBaseObject inParams = virtualMachine.GetMethodParameters("RequestStateChange"))
            {
                inParams["RequestedState"] = ShutDownID;
                using (ManagementBaseObject outParams = virtualMachine.InvokeMethod(
                           "RequestStateChange", inParams, null))
                {
                    try
                    {
                        result = WmiUtilities.ValidateOutput(outParams, scope);
                    }
                    catch (ManagementException e)
                    {
                        Console.WriteLine("");
                    }
                }
            }
            if (result)
            {
                vmStatus = VirtualMachineStatus.PowerOff;
            }
            return(result);
        }
Exemple #6
0
        GetEthernetPortAllocationSettingData(
            ManagementObject parentPort,
            ManagementScope scope)
        {
            string connectionSettingDataQueryWql = string.Format(CultureInfo.InvariantCulture,
                                                                 "SELECT * FROM Msvm_EthernetPortAllocationSettingData WHERE Parent=\"{0}\"",
                                                                 WmiUtilities.EscapeObjectPath(parentPort.Path.Path));

            SelectQuery connectionSettingDataQuery = new SelectQuery(connectionSettingDataQueryWql);

            using (ManagementObjectSearcher connectionSettingDataSearcher = new ManagementObjectSearcher(
                       scope, connectionSettingDataQuery))
                using (ManagementObjectCollection connectionSettingDataCollection =
                           connectionSettingDataSearcher.Get())
                {
                    //
                    // There will always only be one connection per port.
                    //
                    if (connectionSettingDataCollection.Count != 1)
                    {
                        throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                                    "A single Msvm_EthernetPortAllocationSettingData could not be found for " +
                                                                    "parent port \"{0}\"", parentPort.Path.Path));
                    }

                    ManagementObject connectionSettingData =
                        WmiUtilities.GetFirstObjectFromCollection(connectionSettingDataCollection);

                    return(connectionSettingData);
                }
        }
Exemple #7
0
        GetSyntheticEthernetPortSettingData(
            string macAddress,
            ManagementScope scope)
        {
            // Remove any MAC address separators.
            macAddress = macAddress.Replace("-", "").Replace(":", "");

            string portSettingDataQueryWql = string.Format(CultureInfo.InvariantCulture,
                                                           "SELECT * FROM Msvm_SyntheticEthernetPortSettingData WHERE Address=\"{0}\"",
                                                           macAddress);

            SelectQuery portSettingDataQuery = new SelectQuery(portSettingDataQueryWql);

            using (ManagementObjectSearcher portSettingDataSearcher = new ManagementObjectSearcher(
                       scope, portSettingDataQuery))
                using (ManagementObjectCollection portSettingDataCollection =
                           portSettingDataSearcher.Get())
                {
                    if (portSettingDataCollection.Count == 0)
                    {
                        throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                                    "No Msvm_SyntheticEthernetPortSettingData could be found for MAC address \"{0}\"",
                                                                    macAddress));
                    }

                    //
                    // If multiple port setting data instances exist for the requested MAC address, return
                    // the first one.
                    //
                    ManagementObject portSettingData = WmiUtilities.GetFirstObjectFromCollection(
                        portSettingDataCollection);

                    return(portSettingData);
                }
        }
        ConfigureMmioGap(
            string vmName,
            uint gapSize)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
                using (ManagementObject vssd = WmiUtilities.GetVirtualMachineSettings(vm))
                    using (ManagementObject vmms = WmiUtilities.GetVirtualMachineManagementService(scope))
                        using (ManagementBaseObject inParams = vmms.GetMethodParameters("ModifySystemSettings"))
                        {
                            Console.WriteLine("Configuring MMIO gap size of Virtual Machine \"{0}\" ({1}) " +
                                              "to {2} MB...", vm["ElementName"], vm["Name"], gapSize);

                            vssd["LowMmioGapSize"]     = gapSize;
                            inParams["SystemSettings"] = vssd.GetText(TextFormat.CimDtd20);

                            using (ManagementBaseObject outParams =
                                       vmms.InvokeMethod("ModifySystemSettings", inParams, null))
                            {
                                if (WmiUtilities.ValidateOutput(outParams, scope))
                                {
                                    Console.WriteLine("Configuring MMIO gap size succeeded.\n");
                                }
                            }
                        }
        }
Exemple #9
0
        public static void LoadBalancerTest()
        {
            string HvAddr         = "hypervnb://00000000-0000-0000-0000-000000000000/C7240163-6E2B-4466-9E41-FF74E7F0DE47";
            Server detectorServer = new Server(HvAddr);
            //

            var task = new Task(() =>
            {
                detectorServer.StartUpServer();
            });

            task.Start();

            ManagementScope  scope;
            ManagementObject managementService;

            scope             = new ManagementScope(@"\\.\root\virtualization\v2", null);
            managementService = WmiUtilities.GetVirtualMachineManagementService(scope);
            while (Server.mySampleServer.vmPerfDict.Count == 0)
            {
                Thread.Sleep(1000);
            }
            VirtualMachine        vm     = new VirtualMachine("TestVM", scope, managementService);
            List <VirtualMachine> vmlist = new List <VirtualMachine>();

            vmlist.Add(vm);
            LoadBalancer testLoadBalancer = new LoadBalancer(80.0, 1, 50.0, 3, 1, 1000, 200000);

            testLoadBalancer.setDetectorServer(detectorServer);
            testLoadBalancer.BalanceByTime();
            Console.ReadLine();
        }
        VmMigrationSimpleWithNewDataRoot(
            string sourceHost,
            string destinationHost,
            string vmName
            )
        {
            string newDataRoot = "C:\\NewDataRoot";

            ManagementScope srcScope = new ManagementScope(
                @"\\" + sourceHost + @"\root\virtualization\v2", null);

            using (ManagementObject migrationSettingData = GetMigrationSettingData(srcScope))
                using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, srcScope))
                    using (ManagementObject vssd = WmiUtilities.GetVirtualMachineSettings(vm))
                    {
                        migrationSettingData["MigrationType"] = MigrationType.VirtualSystem;
                        migrationSettingData["TransportType"] = TransportType.TCP;

                        vssd["ConfigurationDataRoot"] = newDataRoot;

                        // Perform migration.
                        Console.WriteLine("Performing migration...");
                        Migrate(srcScope,
                                vmName,
                                destinationHost,
                                migrationSettingData.GetText(TextFormat.CimDtd20),
                                vssd.GetText(TextFormat.CimDtd20),
                                null);
                    }
        }
        CompareCompatibilityVectors(
            string hostName,
            string vmName
            )
        {
            bool   isCompatible             = false;
            object vmCompatibilityVectors   = null;
            object hostCompatibilityVectors = null;

            ManagementScope sourceScope = new ManagementScope(
                @"\\" + hostName + @"\root\virtualization\v2", null);

            using (ManagementObject sourceService = GetVirtualMachineMigrationService(sourceScope))
            {
                //
                //Get VM compatibility vectors.
                //
                using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, sourceScope))
                {
                    using (ManagementBaseObject sourceInParams =
                               sourceService.GetMethodParameters("GetSystemCompatibilityVectors"))
                    {
                        sourceInParams["ComputerSystem"] = vm.Path.Path;

                        using (ManagementBaseObject sourceOutParams =
                                   sourceService.InvokeMethod("GetSystemCompatibilityVectors", sourceInParams, null))
                        {
                            WmiUtilities.ValidateOutput(sourceOutParams, sourceScope);
                            vmCompatibilityVectors = sourceOutParams["CompatibilityVectors"];
                        }
                    }
                }

                //
                //Get host compatibility vectors.
                //
                using (ManagementObject host = WmiUtilities.GetHostComputerSystem(hostName, sourceScope))
                {
                    using (ManagementBaseObject sourceInParams =
                               sourceService.GetMethodParameters("GetSystemCompatibilityVectors"))
                    {
                        sourceInParams["ComputerSystem"] = host.Path.Path;

                        using (ManagementBaseObject sourceOutParams =
                                   sourceService.InvokeMethod("GetSystemCompatibilityVectors", sourceInParams, null))
                        {
                            WmiUtilities.ValidateOutput(sourceOutParams, sourceScope);
                            hostCompatibilityVectors = sourceOutParams["CompatibilityVectors"];
                        }
                    }
                }

                isCompatible = CompareVectors(vmCompatibilityVectors, hostCompatibilityVectors);

                if (isCompatible)
                {
                    Console.WriteLine("The VM and host are compatible.\n");
                }
            }
        }
Exemple #12
0
        CheckMigratability(
            ManagementScope scope,
            string vmName,
            string destinationHost,
            string migrationSetting,
            string vssd,
            string[] rasds
            )
        {
            using (ManagementObject service = GetVirtualMachineMigrationService(scope))
                using (ManagementBaseObject inParams =
                           service.GetMethodParameters("MigrateVirtualSystemToHost"))
                    using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
                    {
                        inParams["ComputerSystem"]         = vm.Path.Path;
                        inParams["DestinationHost"]        = destinationHost;
                        inParams["MigrationSettingData"]   = migrationSetting;
                        inParams["NewSystemSettingData"]   = vssd;
                        inParams["NewResourceSettingData"] = rasds;

                        using (ManagementBaseObject outParams =
                                   service.InvokeMethod("CheckVirtualSystemIsMigratable", inParams, null))
                        {
                            return(WmiUtilities.ValidateOutput(outParams, scope, false, true));
                        }
                    }
        }
        MonitorSQoSEvents(
            string hostMachine)
        {
            try
            {
                string wmiQuery;
                ManagementEventWatcher watcher;

                ManagementScope scope = new ManagementScope(
                    @"\\" + hostMachine + @"\root\virtualization\v2", null);

                ManagementObject service = WmiUtilities.GetVirtualMachineManagementService(scope);

                //build the query to monitor the QoS event
                wmiQuery = "Select * From Msvm_StorageAlert";

                watcher = new ManagementEventWatcher(scope, new EventQuery(wmiQuery));
                watcher.EventArrived += new EventArrivedEventHandler(QoSEventHandler);
                watcher.Start();
                Console.WriteLine("Please press ENTER to exit monitoring...\n");
                Console.ReadLine();
                watcher.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
            }
        }
        DeleteSwitch(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Find the switch that we want to delete.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))

                //
                // Now that we have the switch object we can delete it.
                //
                using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                    using (ManagementBaseObject inParams = switchService.GetMethodParameters("DestroySystem"))
                    {
                        inParams["AffectedSystem"] = ethernetSwitch.Path.Path;

                        using (ManagementBaseObject outParams = switchService.InvokeMethod("DestroySystem", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The switch '{0}' was deleted successfully.", switchName));
        }
        ModifyPoolResourcesByPath(
            ManagementScope scope,
            ManagementObject rPConfigurationService,
            string resourceType,
            string resourceSubType,
            string poolPath,
            string[] parentPoolIdArray,
            string[][] parentHostResourcesArray)
        {
            if (parentPoolIdArray.Length == 0)
            {
                throw new ManagementException(string.Format(
                                                  CultureInfo.CurrentCulture,
                                                  @"At least one parent pool must be specified when modifying a 
                    resource pool's host resources (poolPath ""{0}"")", poolPath));
            }

            if (parentPoolIdArray.Length != parentHostResourcesArray.Length)
            {
                throw new ManagementException(string.Format(
                                                  CultureInfo.CurrentCulture,
                                                  @"When modifying a child resource pool's host resources, a host 
                    resource must be specified for each parent pool. Shared allocations 
                    are not supported (poolPath ""{0}"")",
                                                  poolPath));
            }

            string[] parentPoolPathArray =
                ResourcePoolUtilities.GetParentPoolArrayFromPoolIds(
                    scope,
                    resourceType,
                    resourceSubType,
                    parentPoolIdArray);

            string[] resourceAllocationSettingDataArray =
                MsvmResourceAllocationSettingData.GetNewPoolAllocationSettingsArray(
                    scope,
                    resourceType,
                    resourceSubType,
                    parentPoolIdArray,
                    parentHostResourcesArray);

            using (ManagementBaseObject inParams =
                       rPConfigurationService.GetMethodParameters(
                           "ModifyPoolResources"))
            {
                inParams["ChildPool"]          = poolPath;
                inParams["ParentPools"]        = parentPoolPathArray;
                inParams["AllocationSettings"] = resourceAllocationSettingDataArray;

                using (ManagementBaseObject outParams =
                           rPConfigurationService.InvokeMethod(
                               "ModifyPoolResources",
                               inParams,
                               null))
                {
                    WmiUtilities.ValidateOutput(outParams, scope, true, true);
                }
            }
        }
Exemple #16
0
        RequestReplicationStateChange(
            string name,
            UInt16 requestedState)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the Msvm_ComputerSystem.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
            {
                using (ManagementBaseObject inParams =
                           vm.GetMethodParameters("RequestReplicationStateChange"))
                {
                    inParams["RequestedState"] = requestedState;

                    using (ManagementBaseObject outParams =
                               vm.InvokeMethod("RequestReplicationStateChange", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }

                    Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                    "Replication state for virtual machine \"{0}\" is changed to \"{1}\"",
                                                    name, requestedState));
                }
            }
        }
        DeletePoolHelper(
            ManagementScope scope,
            ManagementObject rPConfigurationService,
            string resourceType,
            string resourceSubType,
            string poolId)
        {
            string poolPath =
                MsvmResourcePool.GetResourcePoolPath(
                    scope,
                    resourceType,
                    resourceSubType,
                    poolId);

            using (ManagementBaseObject inParams =
                       rPConfigurationService.GetMethodParameters(
                           "DeletePool"))
            {
                inParams["Pool"] = poolPath;

                using (ManagementBaseObject outParams =
                           rPConfigurationService.InvokeMethod(
                               "DeletePool",
                               inParams,
                               null))
                {
                    WmiUtilities.ValidateOutput(outParams, scope, true, true);
                }
            }
        }
Exemple #18
0
        RemoveReplicationRelationship(
            string name)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the Msvm_ComputerSystem.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
            {
                string vmPath = vm.Path.Path;

                using (ManagementObject replicationService =
                           ReplicaUtilities.GetVirtualMachineReplicationService(scope))
                {
                    using (ManagementBaseObject inParams =
                               replicationService.GetMethodParameters("RemoveReplicationRelationship"))
                    {
                        inParams["ComputerSystem"] = vmPath;

                        using (ManagementBaseObject outParams =
                                   replicationService.InvokeMethod("RemoveReplicationRelationship",
                                                                   inParams,
                                                                   null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }
                }

                Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                "Replication is successfully removed for virtual machine \"{0}\"", name));
            }
        }
Exemple #19
0
        GetMetricDefinition(
            string name,
            ManagementScope scope)
        {
            string metricDefQueryWql = string.Format(CultureInfo.InvariantCulture,
                                                     "SELECT * FROM CIM_BaseMetricDefinition WHERE ElementName=\"{0}\"", name);

            SelectQuery metricDefQuery = new SelectQuery(metricDefQueryWql);

            using (ManagementObjectSearcher metricDefSearcher = new ManagementObjectSearcher(
                       scope, metricDefQuery))
                using (ManagementObjectCollection metricDefCollection = metricDefSearcher.Get())
                {
                    //
                    // There will always only be one metric definition for a given name.
                    //
                    if (metricDefCollection.Count != 1)
                    {
                        throw new ManagementException(string.Format(CultureInfo.CurrentCulture,
                                                                    "A single CIM_BaseMetricDefinition derived instance could not be found " +
                                                                    "for name \"{0}\"", name));
                    }

                    ManagementObject metricDef =
                        WmiUtilities.GetFirstObjectFromCollection(metricDefCollection);

                    return(metricDef);
                }
        }
        public static void DetectVMState(object sender, ElapsedEventArgs e)
        {
            if (DockerDesktopVM == null)
            {
                try
                {
                    ManagementScope  scope;
                    ManagementObject managementService;

                    scope             = new ManagementScope(@"\\.\root\virtualization\v2", null);
                    managementService = WmiUtilities.GetVirtualMachineManagementService(scope);
                    DockerDesktopVM   = new VirtualMachine("DockerDesktopVM", scope, managementService);
                    isDockerInstalled = true;
                }
                catch
                {
                    DockerDesktopVM   = null;
                    isDockerInstalled = false;
                }
            }
            else
            {
                isDockerVMPowerOn = DockerDesktopVM.IsPowerOn();
            }
        }
        SetParentVirtualHardDisk(
            string ServerName,
            string ChildPath,
            string ParentPath,
            string LeafPath,
            string IgnoreIDMismatch)
        {
            ManagementScope scope =
                new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2");

            using (ManagementObject imageManagementService =
                       StorageUtilities.GetImageManagementService(scope))
            {
                using (ManagementBaseObject inParams =
                           imageManagementService.GetMethodParameters("SetParentVirtualHardDisk"))
                {
                    inParams["ChildPath"]        = ChildPath;
                    inParams["ParentPath"]       = ParentPath;
                    inParams["LeafPath"]         = LeafPath;
                    inParams["IgnoreIDMismatch"] = IgnoreIDMismatch;

                    using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                               "SetParentVirtualHardDisk", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }
            }
        }
        public VMState()
        {
            ManagementScope  scope;
            ManagementObject managementService;

            scope             = new ManagementScope(@"\\.\root\virtualization\v2", null);
            managementService = WmiUtilities.GetVirtualMachineManagementService(scope);

            GetConfig configParser = new GetConfig();

            VM1Config = configParser.GetVMConfig("VM1");
            if (VM1Config != null)
            {
                VM1 = new VirtualMachine(VM1Config.VMName, scope, managementService);
            }
            VM2Config = configParser.GetVMConfig("VM2");
            if (VM2Config != null)
            {
                VM2 = new VirtualMachine(VM2Config.VMName, scope, managementService);
            }
            VM3Config = configParser.GetVMConfig("VM3");
            if (VM3Config != null)
            {
                VM3 = new VirtualMachine(VM3Config.VMName, scope, managementService);
            }
            DockerVMConfig = configParser.GetVMConfig("Docker");
        }
        private FileInfo ResizeVhdFile(long FileSizeBefore, long FileSize)
        {
            CheckOS();
            WriteWarning("The VHD file needs to be resized. During the resizing process, the cmdlet will temporarily create a resized file in the same directory as the provided VHD/VHDX file.");

            try
            {
                ManagementScope scope = new ManagementScope(@"\root\virtualization\V2");

                long FullFileSize = FileSize + 512;


                using (ManagementObject imageManagementService =
                           StorageUtilities.GetImageManagementService(scope))
                {
                    CreateBackUp(vhdFileToBeUploaded.FullName);
                    WriteVerbose("Resizing VHD file");
                    using (ManagementBaseObject inParams =
                               imageManagementService.GetMethodParameters("ResizeVirtualHardDisk"))
                    {
                        inParams["Path"]            = vhdFileToBeUploaded.FullName;
                        inParams["MaxInternalSize"] = FileSize;
                        using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                                   "ResizeVirtualHardDisk", inParams, null))
                        {
                            ManagementPath   path            = new ManagementPath((string)outParams["Job"]);
                            ManagementObject job             = new ManagementObject(path);
                            string           jobStatus       = (string)job["JobStatus"];
                            ushort           percentComplete = (ushort)job["PercentComplete"];
                            while (jobStatus == "Job is running" && percentComplete < 100)
                            {
                                Program.SyncOutput.ProgressHyperV(percentComplete, "Resizing VHD");
                                Thread.Sleep(1000);
                                job.Get();
                                jobStatus       = (string)job["JobStatus"];
                                percentComplete = (ushort)job["PercentComplete"];
                            }
                            Program.SyncOutput.ProgressHyperV(percentComplete, "Resizing VHD");
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }
                    WriteVerbose("Resized " + vhdFileToBeUploaded + " from " + FileSizeBefore + " bytes to " + FullFileSize + " bytes.");
                    temporaryFileCreated = true;
                    return(new FileInfo(vhdFileToBeUploaded.FullName));
                }
            }
            catch (System.Management.ManagementException ex)
            {
                if (ex.Message == "Invalid namespace ")
                {
                    Exception outputEx = new Exception("Failed to resize VHD file. Hyper-V Platform is not found.\nFollow this link to enable Hyper-V or resize file manually: https://aka.ms/usingAdd-AzVhd");
                    ThrowTerminatingError(new ErrorRecord(
                                              outputEx,
                                              "Hyper-V is unavailable",
                                              ErrorCategory.InvalidOperation,
                                              null));
                }
                throw ex;
            }
        }
Exemple #24
0
        GetVMGeneration(
            string serverName,
            string vmName)
        {
            ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
                using (ManagementObject vmSettings = WmiUtilities.GetVirtualMachineSettings(vm))
                {
                    string virtualSystemSubType = (string)vmSettings["VirtualSystemSubType"];

                    if (string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:1", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("VM {0} on server {1} is generation 1", vmName, serverName);
                    }
                    else if (string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:2", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("VM {0} on server {1} is generation 2", vmName, serverName);
                    }
                    else
                    {
                        Console.WriteLine("VM {0} on server {1} is an unknown generation", vmName, serverName);
                    }
                }
        }
        CreateReplicationRelationship(
            string name,
            string recoveryServerName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Retrieve the Msvm_ComputerSystem.
            //
            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(name, scope))
            {
                string vmPath = vm.Path.Path;

                using (ManagementObject replicationSettingData =
                           ReplicaUtilities.GetReplicationSettings(vm))
                {
                    replicationSettingData["RecoveryConnectionPoint"]  = recoveryServerName;
                    replicationSettingData["AuthenticationType"]       = 1;
                    replicationSettingData["RecoveryServerPortNumber"] = 80;
                    replicationSettingData["CompressionEnabled"]       = 1;

                    // Keep 24 recovery points.
                    replicationSettingData["RecoveryHistory"] = 24;

                    // Replicate changes after every 300 seconds.
                    replicationSettingData["ReplicationInterval"] = 300;

                    // Take VSS snapshot every one hour.
                    replicationSettingData["ApplicationConsistentSnapshotInterval"] = 1;

                    // Include all disks for replication.
                    replicationSettingData["IncludedDisks"] = WmiUtilities.GetVhdSettings(vm);

                    string settingDataEmbedded =
                        replicationSettingData.GetText(TextFormat.WmiDtd20);

                    using (ManagementObject replicationService =
                               ReplicaUtilities.GetVirtualMachineReplicationService(scope))
                    {
                        using (ManagementBaseObject inParams =
                                   replicationService.GetMethodParameters("CreateReplicationRelationship"))
                        {
                            inParams["ComputerSystem"]         = vmPath;
                            inParams["ReplicationSettingData"] = settingDataEmbedded;

                            using (ManagementBaseObject outParams =
                                       replicationService.InvokeMethod("CreateReplicationRelationship",
                                                                       inParams,
                                                                       null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                    }

                    Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                    "Replication is successfully enabled for virtual machine \"{0}\"", name));
                }
            }
        }
        AttachVirtualHardDisk(
            string ServerName,
            string VirtualHardDiskPath,
            string AssignDriveLetters,
            string ReadOnly)
        {
            ManagementScope scope =
                new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2");

            using (ManagementObject imageManagementService =
                       StorageUtilities.GetImageManagementService(scope))
            {
                using (ManagementBaseObject inParams =
                           imageManagementService.GetMethodParameters("AttachVirtualHardDisk"))
                {
                    inParams["Path"] = VirtualHardDiskPath;
                    inParams["AssignDriveLetter"] = AssignDriveLetters;
                    inParams["ReadOnly"]          = ReadOnly;

                    using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                               "AttachVirtualHardDisk", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }
            }
        }
Exemple #27
0
        GenerateWorldWideNames(
            ManagementScope scope,
            ref WorldWideName wwnA,
            ref WorldWideName wwnB)
        {
            using (ManagementObject settings =
                       WmiUtilities.GetVirtualMachineManagementServiceSettings(scope))
                using (ManagementObject managementService =
                           WmiUtilities.GetVirtualMachineManagementService(scope))
                    using (ManagementBaseObject inParams =
                               managementService.GetMethodParameters("GenerateWwpn"))
                    {
                        // Set WWNN.
                        string assignedWwnn = settings["CurrentWWNNAddress"].ToString();
                        wwnA.NodeName = assignedWwnn;
                        wwnB.NodeName = assignedWwnn;

                        // Generate 2 WWPNs for the 2 sets.
                        inParams["NumberOfWwpns"] = 2;
                        using (ManagementBaseObject outParams =
                                   managementService.InvokeMethod("GenerateWwpn", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);

                            // Requested for 2 WWPNs to be generated.
                            string[] wwpnArray = outParams["GeneratedWwpn"] as string[];
                            wwnA.PortName = wwpnArray[0];
                            wwnB.PortName = wwpnArray[1];
                        }
                    }
        }
        RemoveAuthorizationEntry(
            string primaryHostSystem)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Call the Msvm_ReplicationService::RemoveAuthorizationEntry method.
            //
            using (ManagementObject replicationService =
                       ReplicaUtilities.GetVirtualMachineReplicationService(scope))
            {
                using (ManagementBaseObject inParams =
                           replicationService.GetMethodParameters("RemoveAuthorizationEntry"))
                {
                    inParams["AllowedPrimaryHostSystem"] = primaryHostSystem;

                    using (ManagementBaseObject outParams =
                               replicationService.InvokeMethod("RemoveAuthorizationEntry", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }

                    Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                                    "Replication authorization entry removed for \"{0}\".", primaryHostSystem));
                }
            }
        }
        ResizeVirtualHardDisk(
            string ServerName,
            string VirtualHardDiskPath,
            UInt64 FileSize)
        {
            ManagementScope scope =
                new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2");

            using (ManagementObject imageManagementService =
                       StorageUtilities.GetImageManagementService(scope))
            {
                using (ManagementBaseObject inParams =
                           imageManagementService.GetMethodParameters("ResizeVirtualHardDisk"))
                {
                    inParams["Path"]            = VirtualHardDiskPath;
                    inParams["MaxInternalSize"] = FileSize;

                    using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                               "ResizeVirtualHardDisk", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }
            }
        }
        MergeVirtualHardDisk(
            string ServerName,
            string ChildPath,
            string ParentPath)
        {
            ManagementScope scope =
                new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2");

            using (ManagementObject imageManagementService =
                       StorageUtilities.GetImageManagementService(scope))
            {
                using (ManagementBaseObject inParams =
                           imageManagementService.GetMethodParameters("MergeVirtualHardDisk"))
                {
                    inParams["SourcePath"]      = ChildPath;
                    inParams["DestinationPath"] = ParentPath;

                    using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                               "MergeVirtualHardDisk", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }
            }
        }