Example #1
0
    public void EnableDHCP(ManagementObject mo)
    {
        ManagementBaseObject methodParams = mo.GetMethodParameters("EnableDHCP");
        ManagementBaseObject renewParams = mo.GetMethodParameters("RenewDHCPLease");

        mo.InvokeMethod("EnableDHCP", methodParams, null);
        mo.InvokeMethod("RenewDHCPLease", renewParams, null);
    }
Example #2
0
    public void setDNS(ManagementObject mo, string[] servers)
    {
        ManagementBaseObject methodParams = mo.GetMethodParameters("SetDNSServerSearchOrder");
        methodParams["DNSServerSearchOrder"] = servers;

        try {
            mo.InvokeMethod("SetDNSServerSearchOrder", methodParams, null);
        }
        catch (Exception e) {
            Console.WriteLine("Failed to set DNS", e);
        }
    }
Example #3
0
        ValidateVirtualHardDisk(
            string ServerName,
            string VirtualHardDiskPath)
        {
            ManagementScope scope =
                new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2");

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

                    using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                               "ValidateVirtualHardDisk", inParams, null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope);
                    }
                }
            }
        }
        ModifyPoolSettingsByPath(
            ManagementScope scope,
            ManagementObject rPConfigurationService,
            string poolPath,
            string resourcePoolSettingData)
        {
            using (ManagementBaseObject inParams =
                       rPConfigurationService.GetMethodParameters(
                           "ModifyPoolSettings"))
            {
                inParams["ChildPool"]    = poolPath;
                inParams["PoolSettings"] = resourcePoolSettingData;

                using (ManagementBaseObject outParams =
                           rPConfigurationService.InvokeMethod(
                               "ModifyPoolSettings",
                               inParams,
                               null))
                {
                    WmiUtilities.ValidateOutput(outParams, scope, true, true);
                }
            }
        }
Example #5
0
        RemovePvm(
            string pvmName
            )
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject pvm = WmiUtilities.GetPlannedVirtualMachine(pvmName, scope))
                using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))
                    using (ManagementBaseObject inParams =
                               managementService.GetMethodParameters("DestroySystem"))
                    {
                        inParams["AffectedSystem"] = pvm.Path;

                        Console.WriteLine("Removing Planned Virtual Machine \"{0}\" ({1})...",
                                          pvm["ElementName"], pvm["Name"]);

                        using (ManagementBaseObject outParams =
                                   managementService.InvokeMethod("DestroySystem", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }
        }
Example #6
0
        public uint GetOwnerSid(out string Sid)
        {
            Sid = "";
            ManagementObjectCollection moc = wmi.GetWSqlFromWMI("select * from Win32_Process where Handle='" + this.Handle.ToString() + "'");
            ManagementObject           mop = null;

            foreach (ManagementObject mo in moc)
            {
                mop = mo;
            }
            ManagementBaseObject inbo  = mop.GetMethodParameters("GetOwnerSid");
            ManagementBaseObject outbo = mop.InvokeMethod("GetOwnerSid", inbo, null);
            object a = outbo["Sid"];

            if (a != null)
            {
                Sid = a.ToString();
            }

            uint c = (uint)outbo["ReturnValue"];

            return(c);
        }
Example #7
0
        public static string[] GetMsvmErrorsList(ManagementObject job)
        {
            using (var ip = job?.GetMethodParameters("GetErrorEx"))
                using (var op = job.InvokeMethod("GetErrorEx", ip, null))
                {
                    if ((uint)op?["ReturnValue"] != ReturnCode.Completed)
                    {
                        throw new ManagementException("GetErrorEx() call on the job failed!");
                    }

                    if (op == null)
                    {
                        return(Array.Empty <string>());
                    }

                    if (op["Errors"] is string[] == false)
                    {
                        return(Array.Empty <string>());
                    }

                    return((string[])op["Errors"]);
                }
        }
        void JoinDomain()
        {
            state.value = "InProgress";
            ManagementObject     cs = WmiBase.Singleton.Win32_ComputerSystem;
            ManagementBaseObject mb = cs.GetMethodParameters("JoinDomainOrWorkgroup");

            mb["Name"]         = domainName.value;
            mb["Password"]     = password.value;
            mb["UserName"]     = domainName.value + "\\" + userName.value;
            mb["AccountOU"]    = null;
            mb["FJoinOptions"] = (UInt32)1;
            ManagementBaseObject outParam = cs.InvokeMethod("JoinDomainOrWorkgroup", mb, null);

            if ((UInt32)outParam["returnValue"] == 0)
            {
                state.value = "Succeeded";
            }
            else
            {
                error.value = "" + (UInt32)outParam["returnValue"];
                state.value = "Failed";
            }
        }
Example #9
0
        private static string GetProcessUserName(int pID)
        {
            string str = (string)null;
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher((ObjectQuery) new SelectQuery("Select * from Win32_Process WHERE processID=" + (object)pID));

            try
            {
                using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        ManagementObject     current          = (ManagementObject)enumerator.Current;
                        ManagementBaseObject methodParameters = current.GetMethodParameters("GetOwner");
                        str = current.InvokeMethod("GetOwner", methodParameters, (InvokeMethodOptions)null)["User"].ToString();
                    }
                }
            }
            catch
            {
                str = "SYSTEM";
            }
            return(str);
        }
Example #10
0
        public int RenameRemotePC(String oldName, String newName, String domain, NetworkCredential localaccount, NetworkCredential domainaccount)
        {
            var remoteControlObject = new ManagementPath
            {
                ClassName = "Win32_ComputerSystem",
                Server    = oldName,
                Path      =
                    oldName + "\\root\\cimv2:Win32_ComputerSystem.Name='" + oldName + "'",
                NamespacePath = "\\\\" + oldName + "\\root\\cimv2"
            };

            var conn = new ConnectionOptions
            {
                Authentication   = AuthenticationLevel.PacketPrivacy,
                Impersonation    = ImpersonationLevel.Impersonate,
                EnablePrivileges = true,
                Username         = oldName + "\\" + localaccount.UserName,
                Password         = localaccount.Password
            };

            var remoteScope = new ManagementScope(remoteControlObject, conn);

            remoteScope.Connect();
            var remoteSystem = new ManagementObject(remoteScope, remoteControlObject, null);

            ManagementBaseObject newRemoteSystemName = remoteSystem.GetMethodParameters("Rename");
            var methodOptions = new InvokeMethodOptions();

            newRemoteSystemName.SetPropertyValue("Name", newName);
            newRemoteSystemName.SetPropertyValue("UserName", domainaccount.UserName);
            newRemoteSystemName.SetPropertyValue("Password", domainaccount.Password);

            methodOptions.Timeout = new TimeSpan(0, 10, 0);
            ManagementBaseObject outParams = remoteSystem.InvokeMethod("Rename", newRemoteSystemName, null);

            return((int)outParams.Properties["ReturnValue"].Value);
        }
        /// <summary>
        /// 获取权限字典
        /// </summary>
        /// <param name="repositoryName"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static IDictionary <string, AccessLevel> GetPermissions(string repositoryName, string path)
        {
            ManagementObject repository = GetRepositoryObject(repositoryName);

            if (repository == null)
            {
                return(null);
            }
            ManagementBaseObject inParameters = repository.GetMethodParameters("GetSecurity");

            inParameters["Path"] = path ?? "/";
            ManagementBaseObject outParameters = repository.InvokeMethod("GetSecurity", inParameters, null);

            var permissions = new Dictionary <string, AccessLevel>();

            if (outParameters != null)
            {
                foreach (ManagementBaseObject p in (ManagementBaseObject[])outParameters["Permissions"])
                {
                    var account = (ManagementBaseObject)p["Account"];
                    if (((ManagementBaseObject)p.Properties["Account"].Value).ClassPath.ClassName == "VisualSVN_Group")
                    {
                        var userName    = "******" + (string)account["Name"];
                        var accessLevel = (AccessLevel)p["AccessLevel"];
                        permissions[userName] = accessLevel;
                    }
                    else
                    {
                        var userName    = (string)account["Name"];
                        var accessLevel = (AccessLevel)p["AccessLevel"];
                        permissions[userName] = accessLevel;
                    }
                }
            }

            return(permissions);
        }
Example #12
0
        public void ImportVirtualSystem(string importDirectory, string newMachineName, string machineLocation)
        {
            var scope = new ManagementScope(@"\\" + host + @"\root\virtualization", null);

            using (ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService"))
            {
                ManagementBaseObject importSettingData = GetVirtualSystemImportSettingData(
                    scope, importDirectory, newMachineName, machineLocation);

                using (ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ImportVirtualSystemEx"))
                {
                    inParams["ImportDirectory"]   = importDirectory;
                    inParams["ImportSettingData"] = importSettingData.GetText(TextFormat.CimDtd20);

                    using (ManagementBaseObject outParams = virtualSystemService.InvokeMethod("ImportVirtualSystemEx", inParams, null))
                    {
                        if (outParams == null)
                        {
                            throw new ArgumentException("WMI call returned null!");
                        }
                        uint ret = (UInt32)outParams["ReturnValue"];
                        if (ret == ReturnCode.Started)
                        {
                            if (!Utility.JobCompleted(outParams, scope))
                            {
                                throw new NotSupportedException("Failed to Import VM");
                            }
                        }
                        else if (ret != ReturnCode.Completed)
                        {
                            throw new NotSupportedException(
                                      string.Format(CultureInfo.InvariantCulture, "Import virtual system failed with error:{0}", ret));
                        }
                    }
                }
            }
        }
        private void ExecuteGetScannerCapabilityProfile()
        {
            try
            {
                ManagementObject classInstance =
                    new ManagementObject("root\\CIMV2",
                                         "RSMDriver.Version='2.0.0.1'",
                                         null);

                // Obtain in-parameters for the method
                ManagementBaseObject inParams =
                    classInstance.GetMethodParameters("GetScannerCapabilityProfile");

                // Add the input parameters.
                //inParams["ScannerIdentity"] = inparams[0].Trim();

                //************ Tharindu *************************************

                inParams["ScannerIdentity"] = txtGetCapaScannerID.Text;


                //***********************************************************
                // Execute the method and obtain the return values.
                ManagementBaseObject outParams =
                    classInstance.InvokeMethod("GetScannerCapabilityProfile", inParams, null);

                // List outParams
                textBoxManagementDataDW.AppendText("Out parameters[GetScannerCapabilityProfile]:");
                textBoxManagementDataDW.AppendText("CapabilityProfile: " + outParams["CapabilityProfile"]);
                textBoxManagementDataDW.AppendText("ReturnValue: " + outParams["ReturnValue"]);
                textBoxManagementDataDW.AppendText("\r\n");
            }
            catch (ManagementException err)
            {
                MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
            }
        }
        //string userdesktop = @"c:\Users\" + user + @"\Desktop";
        //string hdrivepath = @"\\dist-win-file-3\homes\" + user;
        //string SourcePath = userdesktop;
        //string DestinationPath = hdrivepath;
        //DirectoryCopy(computer, user, pass, SourcePath, DestinationPath, true);
        public void DirectoryCopy(string computer, string user, string pass, string SourcePath, string DestinationPath, bool Recursive)
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username         = user;
                connection.Password         = pass;
                connection.Impersonation    = ImpersonationLevel.Impersonate;
                connection.EnablePrivileges = true;
                ManagementScope scope = new ManagementScope(
                    @"\\" + computer + @"\root\CIMV2", connection);
                scope.Connect();
                ManagementPath   managementPath = new ManagementPath(@"Win32_Directory.Name='" + SourcePath + "'");
                ManagementObject classInstance  = new ManagementObject(scope, managementPath, null);
                // Obtain in-parameters for the method
                ManagementBaseObject inParams = classInstance.GetMethodParameters("CopyEx");
                // Add the input parameters.
                inParams["FileName"]      = DestinationPath.Replace("\\", "\\\\");
                inParams["Recursive"]     = true;
                inParams["StartFileName"] = null;

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams =
                    classInstance.InvokeMethod("CopyEx", inParams, null);
                // List outParams
                Console.WriteLine((outParams["ReturnValue"]).ToString());
            }
            catch (UnauthorizedAccessException)
            {
                throw new Exception("Access Denied, wrong username or password.");
            }

            catch (ManagementException ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #15
0
        /// <summary>
        /// Updates the TTL, Mapping Flag, Look-up Time out, Cache Time out and Result Domain to the values specified as the input parameters of this method. If a new value for a parameter is not specified, then the current value for the parameter is not changed. The method returns a reference to the modified object as an output parameter.
        /// </summary>
        /// <param name="ttl">Optional - Time, in seconds, that the RR can be cached by a DNS resolver.</param>
        /// <param name="algorithm">Algorithm used with the key specified in the resource record. </param>
        /// <param name="keyTag">Method used to choose a key that verifies an SIG. See RFC 2535, Appendix C for the method used to calculate a KeyTag.</param>
        /// <param name="labels">Unsigned count of labels in the original SIG RR owner name. The count does not include the NULL label for the root, nor any initial wildcards.</param>
        /// <param name="originalTTL">TTL of the RR set signed by the SIG.</param>
        /// <param name="signature">Signature, represented in base 64, formatted as defined in RFC 2535, Appendix A.</param>
        /// <param name="signatureExpiration">Signature expiration date, expressed in seconds since the beginning of January 1, 1970, Greenwich Mean Time (GMT), excluding leap seconds.</param>
        /// <param name="signatureInception">Date and time at which the Signature becomes valid, expressed in seconds since the beginning of January 1, 1970, Greenwich Mean Time (GMT), excluding leap seconds.</param>
        /// <param name="signerName">Domain name of the signer that generated the SIG RR.</param>
        /// <param name="typeCovered">Type of RR covered by this SIG.</param>
        /// <returns>the modified object.</returns>
        public SIGType Modify(TimeSpan?ttl, UInt16 typeCovered,
                              AlgorithmEnum algorithm,
                              UInt16 labels,
                              TimeSpan originalTTL,
                              UnixDateTime signatureExpiration,
                              UnixDateTime signatureInception,
                              UInt16 keyTag,
                              string signerName,
                              string signature)
        {
            ManagementBaseObject inParams = m_mo.GetMethodParameters("Modify");

            if ((ttl != null) && (ttl != this.TTL))
            {
                inParams["TTL"] = ttl.Value.TotalSeconds;
            }

            //these are not optional, need to check if record is deleted if the same
            inParams["Algorithm"]           = (UInt16)algorithm;
            inParams["Labels"]              = labels;
            inParams["OriginalTTL"]         = originalTTL.TotalSeconds;
            inParams["SignatureExpiration"] = signatureExpiration.Unix;
            inParams["SignatureInception"]  = signatureInception.Unix;
            inParams["KeyTag"]              = keyTag;
            inParams["SignerName"]          = signerName;
            inParams["Signature"]           = signature;

            //return new SIGType((ManagementObject)m_mo.InvokeMethod("Modify", inParams, null));
            try
            {
                return(new SIGType(new ManagementObject(m_mo.Scope, new ManagementPath(m_mo.InvokeMethod("Modify", inParams, null)["RR"].ToString()), null)));
            }
            catch (ManagementException me)
            {
                throw new WMIException(me);
            }
        }
        ModifySanSettings(
            string poolId,
            string newPoolId
            )
        {
            Console.WriteLine("Modifying a Virtual SAN's settings:");
            Console.WriteLine("\tSAN Name: {0} (change to {1})", poolId, newPoolId);

            ManagementScope scope = FibreChannelUtilities.GetFcScope();

            using (ManagementObject rpConfigurationService =
                       FibreChannelUtilities.GetResourcePoolConfigurationService(scope))
            {
                string resourcePoolSettingData = FibreChannelUtilities.GetSettingsForPool(scope,
                                                                                          newPoolId,
                                                                                          null);
                string poolPath = FibreChannelUtilities.GetResourcePoolPath(scope, poolId);
                using (ManagementBaseObject inParams =
                           rpConfigurationService.GetMethodParameters("ModifyPoolSettings"))
                {
                    inParams["ChildPool"]    = poolPath;
                    inParams["PoolSettings"] = resourcePoolSettingData;

                    using (ManagementBaseObject outParams =
                               rpConfigurationService.InvokeMethod(
                                   "ModifyPoolSettings",
                                   inParams,
                                   null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope, true, true);
                    }
                }
            }

            Console.WriteLine("Successfully renamed Virtual SAN: from {0} to {1}", poolId, newPoolId);
        }
Example #17
0
/*
 *  /// <summary>
 *  /// Code to execute after the install has completed.
 *  /// </summary>
 *  private void IRServerInstaller_AfterInstall(object sender, InstallEventArgs e)
 *  {
 *    // TODO: Set the restart options here.
 *
 *    // Start the service ...
 *    //using (ServiceController serviceController = new ServiceController(Program.ServiceName))
 *    //serviceController.Start();
 *  }
 */

        /// <summary>
        /// Used to set the "Allow service to interact with the desktop" setting.
        /// </summary>
        private void IRServerInstaller_Committing(object sender, InstallEventArgs e)
        {
            ManagementBaseObject inParam  = null;
            ManagementBaseObject outParam = null;

            try
            {
                ConnectionOptions coOptions = new ConnectionOptions();
                coOptions.Impersonation = ImpersonationLevel.Impersonate;

                ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
                mgmtScope.Connect();

                string path = string.Format("Win32_Service.Name='{0}'", Shared.ServerName);

                using (ManagementObject wmiService = new ManagementObject(path))
                {
                    inParam = wmiService.GetMethodParameters("Change");
                    inParam["DesktopInteract"] = true;
                    inParam["PathName"]        = "\"" + Assembly.GetExecutingAssembly().Location + "\" -SERVICE";
                    outParam = wmiService.InvokeMethod("Change", inParam, null);
                }
            }
            finally
            {
                if (inParam != null)
                {
                    inParam.Dispose();
                }

                if (outParam != null)
                {
                    outParam.Dispose();
                }
            }
        }
        static public void removeTPM(string deviceID)
        {
            string VolumeID = getVolumeID(deviceID);

            ManagementObject classInstance =
                new ManagementObject("root\\CIMV2\\Security\\MicrosoftVolumeEncryption",
                                     "Win32_EncryptableVolume.DeviceID='" + deviceID + "'",
                                     null);

            // Obtain in-parameters for the method
            ManagementBaseObject inParams =
                classInstance.GetMethodParameters("DeleteKeyProtector");

            // Add the input parameters.
            inParams["VolumeKeyProtectorID"] = VolumeID;

            // Execute the method and obtain the return values.
            ManagementBaseObject outParams =
                classInstance.InvokeMethod("DeleteKeyProtector", inParams, null);

            // List outParams
            Console.WriteLine("Out parameters:");
            Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
        }
Example #19
0
        private int JoinWorkgroup(ManagementObject computerSystem, string computerName, string oldDomainName)
        {
            string str;
            ManagementBaseObject methodParameters = computerSystem.GetMethodParameters("JoinDomainOrWorkgroup");

            methodParameters.SetPropertyValue("Name", this._workgroupName);
            methodParameters.SetPropertyValue("UserName", null);
            methodParameters.SetPropertyValue("Password", null);
            methodParameters.SetPropertyValue("FJoinOptions", 0);
            ManagementBaseObject managementBaseObject = computerSystem.InvokeMethod("JoinDomainOrWorkgroup", methodParameters, null);
            int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture);

            if (num != 0)
            {
                Win32Exception win32Exception = new Win32Exception(num);
                if (oldDomainName == null)
                {
                    object[] message = new object[3];
                    message[0] = computerName;
                    message[1] = this._workgroupName;
                    message[2] = win32Exception.Message;
                    str        = StringUtil.Format(ComputerResources.FailToJoinWorkGroup, message);
                }
                else
                {
                    object[] objArray = new object[4];
                    objArray[0] = computerName;
                    objArray[1] = oldDomainName;
                    objArray[2] = this._workgroupName;
                    objArray[3] = win32Exception.Message;
                    str         = StringUtil.Format(ComputerResources.FailToSwitchFromDomainToWorkgroup, objArray);
                }
                this.WriteErrorHelper(str, "FailToJoinWorkGroup", computerName, ErrorCategory.OperationStopped, false, new object[0]);
            }
            return(num);
        }
Example #20
0
        private bool EnterDomain()
        {
            // Invoke WMI to join the domain
            using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
            {
                try
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup");

                    inParams["Name"]         = _long_name;
                    inParams["Password"]     = _admin_password;
                    inParams["UserName"]     = fullAdminUsername;
                    inParams["FJoinOptions"] = 3; // Magic number: 3 = join to domain and create computer account

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);

                    if (int.TryParse(outParams["ReturnValue"].ToString(), out _connect_to_domain_result))
                    {
                        return(_connect_to_domain_result == 0);
                    }
                    else
                    {
                        MessageBox.Show(outParams.GetText(TextFormat.Mof));
                        _connect_to_domain_result = 4;
                        return(false);
                    }
                }
                catch (ManagementException e)
                {
                    _connect_to_domain_result = 4;
                    return(false);
                }
            }
        }
Example #21
0
        /// <summary>
        /// 读取仓库权限
        /// </summary>
        /// <param name="repositoryName">仓库名称</param>
        /// <param name="path">仓库条目路径</param>
        /// <returns></returns>
        public static IDictionary <string, AccessLevel> GetPermissions(string repositoryName, string path)
        {
            ManagementObject     repository   = GetRepositoryObject(repositoryName);
            ManagementBaseObject inParameters = repository.GetMethodParameters("GetSecurity");

            inParameters["Path"] = path;
            ManagementBaseObject outParameters = repository.InvokeMethod("GetSecurity", inParameters, null);

            var permissions = new Dictionary <string, AccessLevel>();

            if (outParameters != null)
            {
                foreach (ManagementBaseObject p in (ManagementBaseObject[])outParameters["Permissions"])
                {
                    var account     = (ManagementBaseObject)p["Account"];
                    var name        = (string)account["Name"];
                    var accessLevel = (AccessLevel)p["AccessLevel"];

                    permissions[name] = accessLevel;
                }
            }

            return(permissions);
        }
Example #22
0
        /// <summary>
        /// Updates the TTL, Priority, Weight, Port, and Domain Name to the values specified as the input parameters of this method. If a new value for a parameter is not specified, then the current value for the parameter is not changed. The method returns a reference to the modified object as an output parameter.
        /// </summary>
        /// <param name="ttl">Optional - Time, in seconds, that the RR can be cached by a DNS resolver.</param>
        /// <param name="domainName">Optional - FQDN of the target host. A target of \.\ means that the service is decidedly not available at this domain.</param>
        /// <param name="port">Optional - Port used on the target host of a protocol service.</param>
        /// <param name="priority">Optional - Priority of the target host specified in the owner name. Lower numbers imply higher priorities.</param>
        /// <param name="weight">Optional - Weight of the target host. This is useful when selecting among hosts that have the same priority. The chances of using this host should be proportional to its weight.</param>
        /// <returns>the modified object.</returns>
        public SRVType Modify(TimeSpan?ttl, UInt16?priority, UInt16?weight, UInt16?port,
                              string srvDomainName)
        {
            ManagementBaseObject inParams = m_mo.GetMethodParameters("Modify");

            if ((ttl != null) && (ttl != this.TTL))
            {
                inParams["TTL"] = ttl.Value.TotalSeconds;
            }

            if ((priority != null) && (priority != this.Priority))
            {
                inParams["Priority"] = priority;
            }
            if ((weight != null) && (weight != this.Weight))
            {
                inParams["Weight"] = weight;
            }
            if ((port != null) && (port != this.Port))
            {
                inParams["Port"] = port;
            }
            if ((!string.IsNullOrEmpty(srvDomainName)) && (srvDomainName != this.SRVDomainName))
            {
                inParams["SRVDomainName"] = IPHelper.FixHostnames(srvDomainName);
            }

            try
            {
                return(new SRVType(new ManagementObject(m_mo.Scope, new ManagementPath(m_mo.InvokeMethod("Modify", inParams, null)["RR"].ToString()), null)));
            }
            catch (ManagementException me)
            {
                throw new WMIException(me);
            }
        }
Example #23
0
        RealizePvm(
            string pvmName
            )
        {
            ManagementObject vm    = null;
            ManagementScope  scope = new ManagementScope(@"root\virtualization\v2");

            using (ManagementObject pvm = WmiUtilities.GetPlannedVirtualMachine(pvmName, scope))
                using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope))
                    using (ManagementBaseObject inParams =
                               managementService.GetMethodParameters("RealizePlannedSystem"))
                    {
                        inParams["PlannedSystem"] = pvm.Path;

                        Console.WriteLine("Realizing Planned Virtual Machine \"{0}\" ({1})...",
                                          pvm["ElementName"], pvm["Name"]);

                        using (ManagementBaseObject outParams =
                                   managementService.InvokeMethod("RealizePlannedSystem", inParams, null))
                        {
                            if (WmiUtilities.ValidateOutput(outParams, scope, true, true))
                            {
                                using (ManagementObject job =
                                           new ManagementObject((string)outParams["Job"]))
                                    using (ManagementObjectCollection pvmCollection =
                                               job.GetRelated("Msvm_ComputerSystem",
                                                              "Msvm_AffectedJobElement", null, null, null, null, false, null))
                                    {
                                        vm = WmiUtilities.GetFirstObjectFromCollection(pvmCollection);
                                    }
                            }
                        }
                    }

            return(vm);
        }
        // This method is used to format the volume.

        static void Main(string[] args)
        {
            try
            {
                ManagementScope Scope;
                Scope = new ManagementScope("\\\\.\\root\\CIMV2", null);

                Scope.Connect();
                ObjectGetOptions     Options       = new ObjectGetOptions();
                ManagementPath       Path          = new ManagementPath("Win32_Volume.DeviceID=\"\\\\\\\\?\\\\Volume{178edf63-2039-11e2-8012-005056c00008}\\\\\"");
                ManagementObject     ClassInstance = new ManagementObject(Scope, Path, Options);
                ManagementBaseObject inParams      = ClassInstance.GetMethodParameters("Format");


                ManagementBaseObject outParams = ClassInstance.InvokeMethod("Format", inParams, null);
                Console.WriteLine("{0,-35} {1,-40}", "Return Value", outParams["ReturnValue"]);
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }
        /// <summary>
        /// 从用户组内删除特定用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static bool DelMemberOnGroup(string userName, string groupName)
        {
            try
            {
                var svn = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null);
                ManagementObject instance = svn.CreateInstance();

                instance.SetPropertyValue("Name", groupName);                                //  过滤组名
                ManagementBaseObject setMember = instance.GetMethodParameters("SetMembers"); //获取 SetMembers 方法

                List <ManagementObject> Member = GetGroupUsersArr(groupName, userName);


                setMember["Members"] = Member.ToArray();

                instance.InvokeMethod("SetMembers", setMember, null);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        EnableCompression(
            string sourceHost
            )
        {
            //
            // Get the service & service setting values.
            //

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

            using (ManagementObject service = GetVirtualMachineMigrationService(scope))
                using (ManagementObject serviceSettings = GetMigrationServiceSettings(service))
                {
                    Console.WriteLine("Is compression enabled: {0}",
                                      serviceSettings["EnableCompression"]);

                    //
                    // Set new setting values.
                    //

                    serviceSettings["EnableCompression"] = true;

                    // Perform service setting change.
                    using (ManagementBaseObject inParams = service.GetMethodParameters("ModifyServiceSettings"))
                    {
                        inParams["ServiceSettingData"] = serviceSettings.GetText(TextFormat.CimDtd20);

                        using (ManagementBaseObject outParams =
                                   service.InvokeMethod("ModifyServiceSettings", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }
                }
        }
Example #27
0
        public static ManagementBaseObject InvokeMethod(ManagementObject mo, string methodName, string propName, string inParamName, uint arg)
        {
            try
            {
                // Obtain in-parameters for the method
                ManagementBaseObject inParams = mo.GetMethodParameters($"{methodName}");

                // Add the input parameters.
                if (inParams != null)
                {
                    inParams[$"{inParamName}"] = arg;
                }

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = mo.InvokeMethod($"{methodName}", inParams, null);

                return((ManagementBaseObject)outParams.Properties[$"{propName}"].Value);
            }
            catch (ManagementException err)
            {
                //MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
                return(null);
            }
        }
Example #28
0
        public static ManagementBaseObject InvokeMethod(ManagementObject mo, string methodName, string propName, string inParamName, uint arg)
        {
            try
            {
                // Obtain in-parameters for the method
                ManagementBaseObject inParams = mo.GetMethodParameters($"{methodName}");

                // Add the input parameters.
                if (inParams != null)
                {
                    inParams[$"{inParamName}"] = arg;
                }

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = mo.InvokeMethod($"{methodName}", inParams, null);

                return((ManagementBaseObject)outParams.Properties[$"{propName}"].Value);
            }
            catch (ManagementException ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
Example #29
0
        /// <summary>
        /// Grants NTFS permissions by SID
        /// </summary>
        /// <param name="path"></param>
        /// <param name="sid"></param>
        /// <param name="permissions"></param>
        /// <param name="inheritParentPermissions"></param>
        /// <param name="preserveOriginalPermissions"></param>
        internal static void GrantNtfsPermissionsBySid(string path, string sid,
                                                       NtfsPermission permissions, bool inheritParentPermissions, bool preserveOriginalPermissions)
        {
            // remove trailing slash if any
            if (path.EndsWith("\\"))
            {
                path = path.Substring(0, path.Length - 1);
            }

            // get security settings
            ManagementObject logicalFileSecuritySetting = wmi.GetObject(String.Format(
                                                                            "Win32_LogicalFileSecuritySetting.Path='{0}'", path));

            // get original security descriptor
            ManagementBaseObject outParams          = logicalFileSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);
            ManagementBaseObject originalDescriptor = ((ManagementBaseObject)(outParams.Properties["Descriptor"].Value));

            // create new descriptor
            ManagementBaseObject descriptor = wmi.GetClass("Win32_SecurityDescriptor").CreateInstance();

            descriptor.Properties["ControlFlags"].Value = inheritParentPermissions ? (uint)33796 : (uint)37892;

            // get original ACEs
            ManagementBaseObject[] originalAces = ((ManagementBaseObject[])(originalDescriptor.Properties["DACL"].Value));

            // create a new ACEs list
            List <ManagementBaseObject> aces = new List <ManagementBaseObject>();

            // copy original ACEs if required
            if (preserveOriginalPermissions)
            {
                foreach (ManagementBaseObject originalAce in originalAces)
                {
                    // we don't want to include inherited and current ACEs
                    ManagementBaseObject objTrustee = (ManagementBaseObject)originalAce.Properties["Trustee"].Value;
                    string trusteeSid   = (string)objTrustee.Properties["SIDString"].Value;
                    bool   inheritedAce = ((AceFlags)originalAce.Properties["AceFlags"].Value & AceFlags.INHERITED_ACE) > 0;
                    if (String.Compare(trusteeSid, sid, true) != 0 && !inheritedAce)
                    {
                        aces.Add(originalAce);
                    }
                }
            }

            // create new trustee object
            ManagementObject trustee = GetTrustee(sid);

            // system access mask
            uint mask = 0;

            if ((permissions & NtfsPermission.FullControl) > 0)
            {
                mask |= 0x1f01ff;
            }
            if ((permissions & NtfsPermission.Modify) > 0)
            {
                mask |= 0x1301bf;
            }
            if ((permissions & NtfsPermission.Write) > 0)
            {
                mask |= 0x100116 | 0x10000 | 0x40;
            }
            if ((permissions & NtfsPermission.Read) > 0)
            {
                mask |= 0x120089;
            }

            bool executeEnabled = ((permissions & NtfsPermission.Execute) > 0);
            bool listEnabled    = ((permissions & NtfsPermission.ListFolderContents) > 0);

            bool equalState = (executeEnabled == listEnabled);


            // create and add to be modified ACE
            ManagementObject ace;

            if (equalState ||
                (permissions & NtfsPermission.FullControl) > 0 ||
                (permissions & NtfsPermission.Modify) > 0)                 // both "Execute" and "List" enabled or disabled
            {
                if ((permissions & NtfsPermission.Execute) > 0)
                {
                    mask |= (uint)SystemAccessMask.FILE_TRAVERSE;
                }

                ace               = wmi.GetClass("Win32_Ace").CreateInstance();
                ace["Trustee"]    = trustee;
                ace["AceFlags"]   = AceFlags.OBJECT_INHERIT_ACE | AceFlags.CONTAINER_INHERIT_ACE;
                ace["AceType"]    = 0;              // "Allow" type
                ace["AccessMask"] = mask;
                aces.Add(ace);
            }
            else             // either "Execute" or "List" enabled or disabled
            {
                // we should place a separate permissions for folders and files
                // add FOLDER specific permissions
                uint foldersMask = mask;
                if ((permissions & NtfsPermission.ListFolderContents) > 0)
                {
                    foldersMask |= (uint)SystemAccessMask.FILE_TRAVERSE;
                }

                ace               = wmi.GetClass("Win32_Ace").CreateInstance();
                ace["Trustee"]    = trustee;
                ace["AceFlags"]   = AceFlags.CONTAINER_INHERIT_ACE;
                ace["AceType"]    = 0;              // "Allow" type
                ace["AccessMask"] = foldersMask;    // set default permissions
                aces.Add(ace);

                // add files specific permissions
                uint filesMask = mask;
                if ((permissions & NtfsPermission.Execute) > 0)
                {
                    filesMask |= (uint)SystemAccessMask.FILE_TRAVERSE;
                }

                ace               = wmi.GetClass("Win32_Ace").CreateInstance();
                ace["Trustee"]    = trustee;
                ace["AceFlags"]   = AceFlags.OBJECT_INHERIT_ACE;
                ace["AceType"]    = 0;              // "Allow" type
                ace["AccessMask"] = filesMask;      // set default permissions
                aces.Add(ace);
            }

            // set newly created ACEs
            ManagementBaseObject[] newAces = aces.ToArray();
            descriptor.Properties["DACL"].Value = newAces;

            // set security descriptor
            ManagementBaseObject inParams = logicalFileSecuritySetting.GetMethodParameters("SetSecurityDescriptor");

            inParams["Descriptor"] = descriptor;
            outParams = logicalFileSecuritySetting.InvokeMethod("SetSecurityDescriptor", inParams, null);

            // check results
            uint result = (uint)(outParams.Properties["ReturnValue"].Value);

            logicalFileSecuritySetting.Dispose();
        }
        /// <summary>
        /// Creates a new IIS virtual server.
        /// </summary>
        /// <param name="virtualServer">Virtual server to create.</param>
        /// <param name="start">Start the virtual server.</param>
        /// <returns>Virtual server with updated path.</returns>
        public /*VirtualServer*/ void Create(VirtualServer virtualServer, bool start)
        {
            ManagementPath createPath = new ManagementPath();

            createPath.RelativePath = "IIsWebService.Name='W3SVC'";
            ManagementObject management = new ManagementObject(
                WmiScope, createPath, null);

            ManagementBaseObject inParams =
                management.GetMethodParameters("CreateNewSite");

            inParams["PathOfRootVirtualDir"] = virtualServer.HomeDirectory;
            inParams["ServerBindings"]       = virtualServer.GetBaseObjectBindings(this);
            inParams["ServerComment"]        = virtualServer.Description;

            // Execute the CreateNewSite method and get returned params.
            ManagementBaseObject outParams = management.
                                             InvokeMethod("CreateNewSite", inParams, null);

            // Set the new site path.
            virtualServer.Path = new VirtualServerPath(
                outParams.Properties["ReturnValue"].Value.ToString());

            ManagementPath settingsPath = new ManagementPath();

            settingsPath.RelativePath = virtualServer.Path;
            settingsPath.ClassName    = "IIsWebServerSetting";

            ManagementObject siteSettings =
                new ManagementObject(WmiScope, settingsPath, null);
            PropertyDataCollection properties = siteSettings.Properties;

            // If anonymous access is set, then set the anonymous user values.
            if ((virtualServer.AuthFlags & VirtualServerAuthFlag.Anonymous) != 0)
            {
                WindowsUser user = virtualServer.AnonymousUser;
                properties["AnonymousUserName"].Value = user.Username;
                properties["AnonymousUserPass"].Value = user.Password;
            }

            // Set only if specified, otherwise DefaultAppPool is used.
            if (!string.IsNullOrEmpty(virtualServer.ApplicationPool))
            {
                properties["AppPoolId"].Value =
                    virtualServer.ApplicationPool;
            }

            // Apply access, auth and application pool values.
            properties["AuthFlags"].Value   = (int)virtualServer.AuthFlags;
            properties["AccessFlags"].Value = (int)virtualServer.AccessFlags;

            // Update the settings.
            siteSettings.Put();

            // Take the ID for the virtual server and use root folder.
            ManagementPath rootSettingsPath = new ManagementPath(
                String.Format(
                    "IIsWebVirtualDirSetting='W3SVC/{0}/ROOT'",
                    virtualServer.Path.Id));

            ManagementObject rootSettings =
                new ManagementObject(WmiScope, rootSettingsPath, null);
            PropertyDataCollection rootProperties = rootSettings.Properties;

            // Assign AppFriendlyName always; it may be in the DefaultAppPool.
            rootProperties["AppFriendlyName"].Value = virtualServer.Description;
            rootProperties["HttpRedirect"].Value    = virtualServer.HttpRedirect;
            rootSettings.Put();

            if (start)
            {
                // Start the virtual server if parameter is true.
                this.ChangeState(virtualServer, VirtualServerState.Start);
            }

            //return virtualServer;
        }
Example #31
0
        public LocalIpSet()
        {
            NetworkChange.NetworkAddressChanged += (object sender, EventArgs e) => {
                // 延迟获取网络信息以防止立即获取时获取不到
                TimeSpan.FromSeconds(1).Delay().ContinueWith(t => {
                    var old   = _localIps;
                    _isInited = false;
                    InitOnece();
                    var localIps = _localIps;
                    if (localIps.Length == 0)
                    {
                        VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), "网络连接已断开", toConsole: true);
                    }
                    else
                    {
                        if (old.Length == 0)
                        {
                            VirtualRoot.ThisLocalInfo(nameof(LocalIpSet), "网络连接已连接", toConsole: true);
                        }
                        else
                        {
                            bool isIpChanged = false;
                            if (old.Length != localIps.Length)
                            {
                                isIpChanged = true;
                            }
                            else
                            {
                                foreach (var item in localIps)
                                {
                                    var oldItem = old.FirstOrDefault(a => a.SettingID == item.SettingID);
                                    if (item != oldItem)
                                    {
                                        isIpChanged = true;
                                        break;
                                    }
                                }
                            }
                            VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), $"网络接口的 IP 地址发生了 {(isIpChanged ? "变更" : "刷新")}", toConsole: true);
                        }
                    }
                });
            };
            NetworkChange.NetworkAvailabilityChanged += (object sender, NetworkAvailabilityEventArgs e) => {
                if (e.IsAvailable)
                {
                    VirtualRoot.ThisLocalInfo(nameof(LocalIpSet), $"网络可用", toConsole: true);
                }
                else
                {
                    VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), $"网络不可用", toConsole: true);
                }
            };
            VirtualRoot.BuildCmdPath <SetLocalIpCommand>(action: message => {
                ManagementObject mo = null;
                using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration")) {
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject item in moc)
                    {
                        if ((string)item["SettingID"] == message.Input.SettingID)
                        {
                            mo = item;
                            break;
                        }
                    }
                }
                if (mo != null)
                {
                    if (message.Input.DHCPEnabled)
                    {
                        mo.InvokeMethod("EnableStatic", null);
                        mo.InvokeMethod("SetGateways", null);
                        mo.InvokeMethod("EnableDHCP", null);
                    }
                    else
                    {
                        ManagementBaseObject inPar = mo.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"]         = new string[] { message.Input.IPAddress };
                        inPar["SubnetMask"]        = new string[] { message.Input.IPSubnet };
                        mo.InvokeMethod("EnableStatic", inPar, null);
                        inPar = mo.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = new string[] { message.Input.DefaultIPGateway };
                        mo.InvokeMethod("SetGateways", inPar, null);
                    }

                    if (message.IsAutoDNSServer)
                    {
                        mo.InvokeMethod("SetDNSServerSearchOrder", null);
                    }
                    else
                    {
                        ManagementBaseObject inPar    = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = new string[] { message.Input.DNSServer0, message.Input.DNSServer1 };
                        mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                    }
                }
            });
        }
Example #32
0
        protected override void ProcessRecord()
        {
            String WmiRecordClassName = Enum.GetName(typeof(WmiRecordClass), RecordType);

            #region Check / Fix Name parameter
            if (Name == "@" | Name == String.Empty)
            {
                Name = ZoneName;
            }
            else if (RecordType == RecordType.PTR)
            {
                Regex IPMatch = new Regex(@"^\d{1,3}(?:\.\d{1,3}){3}$");
                if (IPMatch.IsMatch(Name))
                {
                    IPAddress IP = IPAddress.Parse(Name);
                    if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        Byte[] IPBytes = IP.GetAddressBytes();
                        Name = String.Format("{0}.{1}.{2}.{3}.in-addr.arpa.",
                                             IPBytes[3],
                                             IPBytes[2],
                                             IPBytes[1],
                                             IPBytes[0]);
                    }
                }
            }
            if (!Name.Contains(ZoneName))
            {
                Name = Name.TrimEnd('.');
                Name = String.Format("{0}.{1}", Name, ZoneName);
            }
            #endregion

            #region Parameter Set validation
            Boolean Terminate = false;
            switch (ParameterSetName)
            {
            case "PS0": break;

            case "PS1":
                if (WmiRecordClassName != "MicrosoftDNS_AType" &
                    WmiRecordClassName != "MicrosoftDNS_AAAAType" &
                    WmiRecordClassName != "MicrosoftDNS_WKSType")
                {
                    Terminate = true;
                }
                break;

            case "PS2":
                if (WmiRecordClassName != "MicrosoftDNS_CNAMEType" &
                    WmiRecordClassName != "MicrosoftDNS_MBType" &
                    WmiRecordClassName != "MicrosoftDNS_MDType" &
                    WmiRecordClassName != "MicrosoftDNS_MFType" &
                    WmiRecordClassName != "MicrosoftDNS_NSType" &
                    WmiRecordClassName != "MicrosoftDNS_PTRType")
                {
                    Terminate = true;
                }
                break;

            case "PS3":
                if (WmiRecordClassName != "MicrosoftDNS_MGType" &
                    WmiRecordClassName != "MicrosoftDNS_MRType")
                {
                    Terminate = true;
                }
                break;

            case "PS4":
                if (WmiRecordClassName != "MicrosoftDNS_TXTType")
                {
                    Terminate = true;
                }
                break;

            case "PS5":
                if (WmiRecordClassName != "MicrosoftDNS_HINFOType")
                {
                    Terminate = true;
                }
                break;

            case "PS6":
                if (WmiRecordClassName != "MicrosoftDNS_ISDNType")
                {
                    Terminate = true;
                }
                break;

            case "PS7":
                if (WmiRecordClassName != "MicrosoftDNS_MINFOType")
                {
                    Terminate = true;
                }
                break;

            case "PS8":
                if (WmiRecordClassName != "MicrosoftDNS_NXTType")
                {
                    Terminate = true;
                }
                break;

            case "PS9":
                if (WmiRecordClassName != "MicrosoftDNS_RPType")
                {
                    Terminate = true;
                }
                break;

            case "PS10":
                if (WmiRecordClassName != "MicrosoftDNS_AFSDBType")
                {
                    Terminate = true;
                }
                break;

            case "PS11":
                if (WmiRecordClassName != "MicrosoftDNS_MXType" &
                    WmiRecordClassName != "MicrosoftDNS_RTType")
                {
                    Terminate = true;
                }
                break;

            case "PS12":
                if (WmiRecordClassName != "MicrosoftDNS_X25Type")
                {
                    Terminate = true;
                }
                break;

            case "PS14":
                if (WmiRecordClassName != "MicrosoftDNS_SRVType")
                {
                    Terminate = true;
                }
                break;

            case "PS15":
                if (WmiRecordClassName != "MicrosoftDNS_WINSType")
                {
                    Terminate = true;
                }
                break;

            case "PS16":
                if (WmiRecordClassName != "MicrosoftDNS_WINSRType")
                {
                    Terminate = true;
                }
                break;
            }

            if (Terminate)
            {
                WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException("InvalidParameterSetForRecordType"),
                        "InvalidOperation",
                        ErrorCategory.InvalidOperation,
                        typeof(ManagementCmdlet)));
            }
            #endregion

            #region Extended parameters validation
            Terminate = false;
            switch (RecordType)
            {
            case RecordType.A:
            case RecordType.AAAA:
                if (IPAddress == null)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("IP Address must be specified"),
                            "AddressRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.WKS:
                if (IPAddress == null | IPProtocol == String.Empty | Services[0] == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("InternetAddress, IPProtocol and Services must be specified"),
                            "InternetAddressAndIPProtocolAndServicesRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.CNAME:
            case RecordType.MB:
            case RecordType.MD:
            case RecordType.MF:
            case RecordType.NS:
            case RecordType.PTR:
                if (Hostname == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("Hostname must be specified"),
                            "HostnameRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.MG:
            case RecordType.MR:
                if (MailboxName == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("MailboxName must be specified"),
                            "MailboxNameRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.TXT:
                if (Text == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("Text must be specified"),
                            "TextRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.HINFO:
                if (CPU == String.Empty & OS == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("CPU or OS must be specified"),
                            "CPUOrOSRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.ISDN:
                if (ISDNNumber == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("ISDNNumber must be specified"),
                            "ISDNNumberRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.MINFO:
                if (ResponsibleMailbox == String.Empty | ErrorMailbox == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("ResponsibleMailbox and ErrorMailbox must be specified"),
                            "ResponsibleMailboxAndErrorMailboxRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            //case RecordType.NXT:
            //    if (NextDomainName == String.Empty)
            //    {
            //        ThrowTerminatingError(
            //            new ErrorRecord(
            //                new PSInvalidOperationException("NextDomainName must be specified"),
            //                "NextDomainNameRequired",
            //                ErrorCategory.InvalidArgument,
            //                typeof(DnsShellManagementCmdlet)));
            //    }
            //    break;
            case RecordType.RP:
                if (TXTDomainName == String.Empty | ResponsibleMailbox == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("TXTDomainName and ResponsibleMailbox must be specified"),
                            "TXTDomainNameAndResponsibleMailboxRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.AFSDB:
                if (TargetName == String.Empty | SubType == UInt16.MaxValue)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("TargetName and SubType must be specified"),
                            "TargetNameRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.MX:
            case RecordType.RT:
                if (TargetName == String.Empty | Preference == UInt16.MaxValue)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("TargetName and Preference must be specified"),
                            "TargetNameRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.SRV:
                if (TargetName == String.Empty | Port == UInt16.MaxValue)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("TargetName and Port must be specified"),
                            "TargetNameAndResponsibleMailboxRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.WINS:
                if (WinsServers[0] == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("WinsServers must be specified"),
                            "WinsServersRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.WINSR:
                if (ResultDomain == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("ResultDomain must be specified"),
                            "ResultDomainRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;

            case RecordType.X25:
                if (PSDNAddress == String.Empty)
                {
                    WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException("PSDN Address must be specified"),
                            "PSDNAddressRequired",
                            ErrorCategory.InvalidArgument,
                            typeof(ManagementCmdlet)));
                }
                break;
            }
            #endregion

            if (ShouldProcess(String.Format("Name: {0} Type: {1} Zone: {2}", Name, RecordType, ZoneName)))
            {
                base.SetOptions();
                base.SetScope(Server);
                base.SetManagementPath("MicrosoftDNS_Server");

                String DnsServerName = String.Empty;

                ManagementObjectCollection WmiServers = base.Search("");
                foreach (ManagementObject WmiServer in WmiServers)
                {
                    DnsServerName = (String)WmiServer.Properties["Name"].Value;
                }

                this.SetManagementPath(WmiRecordClassName);

                ManagementObject WmiRecordClass = this.GetClass();
                String           NewPath        = String.Empty;

                ManagementBaseObject inParams = WmiRecordClass.GetMethodParameters("CreateInstanceFromPropertyData");
                inParams["DnsServerName"] = DnsServerName;
                inParams["ContainerName"] = ZoneName;
                inParams["OwnerName"]     = Name;
                if (TTL != 0)
                {
                    inParams["TTL"] = TTL;
                }

                switch (WmiRecordClassName)
                {
                case "MicrosoftDNS_AType":
                    if (IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        inParams["IPAddress"] = IPAddress;
                    }
                    else
                    {
                        WriteError(
                            new ErrorRecord(
                                new PSInvalidOperationException("Invalid IP Address"),
                                "InvalidIPAddress",
                                ErrorCategory.InvalidArgument,
                                typeof(ManagementCmdlet)));
                    }
                    break;

                case "MicrosoftDNS_AAAAType":
                    if (IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {
                        inParams["IPv6Address"] = IPAddress;
                    }
                    else
                    {
                        WriteError(
                            new ErrorRecord(
                                new PSInvalidOperationException("Invalid IPv6 Address"),
                                "InvalidIPv6Address",
                                ErrorCategory.InvalidArgument,
                                typeof(ManagementCmdlet)));
                    }
                    break;

                case "MicrosoftDNS_AFSDBType":
                    inParams["ServerName"] = TargetName;
                    inParams["Subtype"]    = SubType;
                    break;

                case "MicrosoftDNS_CNAMEType":
                    inParams["PrimaryName"] = Hostname;
                    break;

                case "MicrosoftDNS_HINFOType":
                    inParams["CPU"] = CPU;
                    inParams["OS"]  = OS;
                    break;

                case "MicrosoftDNS_ISDNType":
                    inParams["ISDNNumber"] = ISDNNumber;
                    inParams["SubAddress"] = SubAddress;
                    break;

                case "MicrosoftDNS_MBType":
                    inParams["MBHost"] = Hostname;
                    break;

                case "MicrosoftDNS_MDType":
                    inParams["MDHost"] = Hostname;
                    break;

                case "MicrosoftDNS_MFType":
                    inParams["MFHost"] = Hostname;
                    break;

                case "MicrosoftDNS_MGType":
                    inParams["MGMailbox"] = MailboxName;
                    break;

                case "MicrosoftDNS_MINFOType":
                    inParams["ResponibleMailbox"] = ResponsibleMailbox;
                    inParams["ErrorMailbox"]      = ErrorMailbox;
                    break;

                case "MicrosoftDNS_MRType":
                    inParams["MRMailbox"] = MailboxName;
                    break;

                case "MicrosoftDNS_MXType":
                    inParams["MailExchange"] = TargetName;
                    inParams["Preference"]   = Preference;
                    break;

                case "MicrosoftDNS_NSType":
                    inParams["NSHost"] = Hostname;
                    break;

                case "MicrosoftDNS_PTRType":
                    inParams["PTRDomainName"] = Hostname;
                    break;

                case "MicrosoftDNS_RPType":
                    inParams["RPMailbox"]     = ResponsibleMailbox;
                    inParams["TXTDomainName"] = TXTDomainName;
                    break;

                case "MicrosoftDNS_RTType":
                    inParams["IntermediateHost"] = TargetName;
                    inParams["Preference"]       = Preference;
                    break;

                case "MicrosoftDNS_SRVType":
                    inParams["Port"]     = Port;
                    inParams["Priority"] = Priority;
                    // This will fail against Windows 2003?
                    inParams["SRVDomainName"] = TargetName;
                    inParams["Weight"]        = Weight;
                    break;

                case "MicrosoftDNS_TXTType":
                    inParams["DescriptiveText"] = Text;
                    break;

                case "MicrosoftDNS_WINSType":
                    foreach (String WinsServer in WinsServers)
                    {
                        if (!IsValidIPAddress(WinsServer))
                        {
                            WriteError(
                                new ErrorRecord(
                                    new PSInvalidOperationException("Invalid IP Address"),
                                    "InvalidIPAddress",
                                    ErrorCategory.InvalidArgument,
                                    typeof(ManagementCmdlet)));
                        }
                    }
                    inParams["CacheTimeout"]  = CacheTimeout;
                    inParams["LookupTimeout"] = LookupTimeout;
                    inParams["MappingFlag"]   = MappingFlag;
                    inParams["WinsServers"]   = String.Join(" ", WinsServers);
                    break;

                case "MicrosoftDNS_WINSRType":
                    inParams["CacheTimeout"]  = CacheTimeout;
                    inParams["LookupTimeout"] = LookupTimeout;
                    inParams["MappingFlag"]   = MappingFlag;
                    inParams["ResultDomain"]  = ResultDomain;
                    break;

                case "MicrosoftDNS_WKSType":
                    inParams["InternetAddress"] = IPAddress;
                    inParams["IPProtocol"]      = IPProtocol;
                    inParams["Services"]        = String.Join(" ", Services);
                    break;

                case "MicrosoftDNS_X25Type":
                    inParams["PSDNAddress"] = IPAddress;
                    break;

                default:
                    WriteError(
                        new ErrorRecord(
                            new PSNotSupportedException("Unsupported Record Type"),
                            "NotSupported",
                            ErrorCategory.NotImplemented,
                            typeof(ManagementCmdlet)));
                    break;
                }

                ManagementBaseObject outParams = WmiRecordClass.InvokeMethod(
                    "CreateInstanceFromPropertyData", inParams, null);

                NewPath = (String)outParams["RR"];

                if (PassThru)
                {
                    this.SetManagementPath(NewPath);
                    ManagementObject WmiRecord = this.Get();

                    WriteRecord(WmiRecord);
                }
            }
        }
Example #33
0
    public void setIP(ManagementObject objMO, string IPAddress, string SubnetMask, string Gateway)
    {
        try {
            ManagementBaseObject objNewIP, objNewGate, objNewDns;
            objNewIP = objMO.GetMethodParameters("EnableStatic");
            objNewGate = objMO.GetMethodParameters("SetGateways");
            objNewDns = objMO.GetMethodParameters("EnableDNS");

            objNewGate["DefaultIPGateway"] = new string[] { Gateway };
            objNewGate["GatewayCostMetric"] = new int[] { 1 };
            objNewIP["IPAddress"] = new string[] { IPAddress };
            objNewIP["SubnetMask"] = new string[] { SubnetMask };
            //objNewDns["DNSServerSearchOrder"] = new string[] { DNS1, DNS2 };

            objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDns, null);
            objMO.InvokeMethod("EnableStatic", objNewIP, null);
            objMO.InvokeMethod("SetGateways", objNewGate, null);

            //MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!");
        }
        catch (Exception ex) {
            MessageBox.Show("Unable to Set IP : " + ex.Message);
        }
    }