private void CreateOrUpdate() { if (string.IsNullOrEmpty(this.WindowsGroup)) { Log.LogError("WindowsGroup is required."); return; } PutOptions options = new PutOptions { Type = PutType.UpdateOrCreate }; using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_HostSetting"), null)) { ManagementObject btsHostSetting = instance.CreateInstance(); if (btsHostSetting == null) { Log.LogError("There was a failure creating the MSBTS_HostSetting instance"); return; } btsHostSetting["Name"] = this.HostName; btsHostSetting["HostType"] = this.hostType; btsHostSetting["NTGroupName"] = this.WindowsGroup; btsHostSetting["AuthTrusted"] = this.Trusted; btsHostSetting["MgmtDbServerOverride"] = this.DatabaseServer; btsHostSetting["IsHost32BitOnly"] = this.Use32BitHostOnly; if (this.hostType == BizTalkHostType.InProcess) { btsHostSetting.SetPropertyValue("HostTracking", this.Tracking); btsHostSetting.SetPropertyValue("IsDefault", this.Default); } if (!string.IsNullOrEmpty(this.AdditionalHostSettings)) { string[] additionalproperties = this.AdditionalHostSettings.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in additionalproperties) { string[] property = s.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); btsHostSetting[property[0]] = property[1]; } } btsHostSetting.Put(options); this.explorer.SaveChanges(); } }
/// <summary> /// Set the slidebar status. Just like SetAppRegistration. /// This function is also written by DOSSTONED /// </summary> /// <param name="evt">Event to set.</param> /// <param name="enabled">Whether this event is enabled.</param> public byte[] SetSlideBarStatus(Event evt, bool enabled) { byte[] array = new byte[128]; array[0] = 1; array[1] = 16; array[8] = (byte)evt; array[9] = 3; array[10] = 0; array[16] = (byte)(enabled ? 1 : 0); array[68] = (byte)(enabled ? 1 : 0); SelectQuery query = new SelectQuery("WMIACPI_IO"); ManagementScope scope = new ManagementScope("root\\WMI"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; managementObject.SetPropertyValue("IOBytes", array); managementObject.Put(); } } if (managementObjectSearcher != null) { managementObjectSearcher.Dispose(); } return(array); }
/// <summary> /// Write the bytes into WMIACPI_IO /// </summary> /// <param name="ioBytes">Raw bytes, length = 128</param> /// <returns>True if success</returns> private bool WriteWMIACPI_IO(byte[] ioBytes) { try { if (ioBytes.GetLength(0) != (int)this.IOBytesLength) { bool result = false; return(result); } SelectQuery query = new SelectQuery(this.WMIACPIIOClass); ManagementScope scope = new ManagementScope(this.WMIACPINamespace); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; managementObject.SetPropertyValue("IOBytes", ioBytes); managementObject.Put(); bool result = true; return(result); } } } catch (ManagementException ex) { //base.DebugInfoTrace(ex); } //catch (Exception ex2) //{ // //base.DebugInfoTrace(ex2); //} return(false); }
public void ApplyConfiguration(InstanceConfiguration configuration) { ManagementObject.SetPropertyValue("LogMessagesAtServiceLevel", configuration.LogMessageAtServiceLevel); ManagementObject.SetPropertyValue("TraceLevel", configuration.ServiceModelTraceLevel); ManagementObject.Put(); Configuration = InstanceConfiguration.ReadFromWmi(ManagementObject); }
private bool WriteWMIACPI_IO(byte[] ioBytes) { if (ioBytes.GetLength(0) != 128) { return(false); } SelectQuery query = new SelectQuery("WMIACPI_IO"); ManagementScope scope = new ManagementScope("root\\WMI"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; managementObject.SetPropertyValue("IOBytes", ioBytes); managementObject.Put(); return(true); } } if (managementObjectSearcher != null) { managementObjectSearcher.Dispose(); } return(false); }
/// <summary> /// 设置用户隶属用户组 /// </summary> /// <param name="userName"></param> /// <param name="groupName"></param> /// <returns></returns> public static bool AddMemberToGroup(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); // 添加本次新用户 Member.Add(new ManagementObject("root\\VisualSVN", string.Format("VisualSVN_User.Name='{0}'", userName), null)); setMember["Members"] = Member.ToArray(); instance.InvokeMethod("SetMembers", setMember, null); return(true); } catch (Exception) { return(false); } }
private void buttonSet8And68_Click(object sender, EventArgs e) { byte[] array = new byte[128]; array[0] = 1; array[1] = 16; array[8] = (byte)numericUpDown1.Value; array[9] = 3; array[10] = 0; array[16] = (byte)numericUpDown2.Value; SelectQuery query = new SelectQuery("WMIACPI_IO"); ManagementScope scope = new ManagementScope("root\\WMI"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; managementObject.SetPropertyValue("IOBytes", array); managementObject.Put(); } } if (managementObjectSearcher != null) { managementObjectSearcher.Dispose(); } }
/// <summary> /// Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { ManagementObject mo = GetreceiveLocationWmiObject(ReceiveLocationName); bool isActualEnabled; using (mo) { isActualEnabled = (bool)mo.GetPropertyValue("OperatingWindowEnabled"); } if (Enable != isActualEnabled) { PutOptions p = new PutOptions(); p.Type = PutType.UpdateOnly; mo.SetPropertyValue("OperatingWindowEnabled", Enable); ManagementPath result = mo.Put(p); context.LogInfo(string.Format("The receive location: {0} service window is {1}", ReceiveLocationName, Enable ? "enabled" : "disabled")); } else { context.LogInfo(string.Format("The receive location: {0} service windows was already in the state {1}", ReceiveLocationName, Enable ? "enabled" : "disabled")); } }
/// <summary> /// 重命名Tap设备 /// </summary> /// <param name="name">新名字</param> /// <param name="adapter">Tap设备</param> public static void RenameTapDevice(string name, NetworkInterface adapter) { if (Os.Ver == Os.V.XpOrLower) { throw new NotSupportedException("Windows Version Too Low"); } if (Os.Ver == Os.V.VistaOrSeven) { // win7 or lower ManagementClass nic = new ManagementClass(@"\\.\ROOT\cimv2:Win32_NetworkAdapter"); ManagementObject target = null; foreach (ManagementObject a in nic.GetInstances()) { if ((string)a["GUID"] == adapter.Id) { target = a; break; } } if (target != null) { target.SetPropertyValue("NetConnectionID", name); PutOptions po = new PutOptions { Type = PutType.UpdateOnly }; target.Put(po); } } else { // win8 or higher ManagementClass nic = new ManagementClass(@"\\.\ROOT\StandardCimv2:MSFT_NetAdapter"); ManagementObject target = null; foreach (ManagementObject a in nic.GetInstances()) { if ((string)a["DeviceID"] == adapter.Id) { target = a; break; } } if (target != null) { ManagementBaseObject param = target.GetMethodParameters("Rename"); param["NewName"] = name; target.InvokeMethod("Rename", param, null); } } /* * else { * // xp or lower,不确定是否有效(win7测试无效) * string adapterKey = @"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\" + adapter.Id + @"\Connection"; * RegistryKey rbase = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); * RegistryKey rk = rbase.OpenSubKey(adapterKey, true); * rk?.SetValue("Name", name); * } */ }
private static bool WriteWMIACPI_IO(WMIACPI_IO_Status status) { byte[] array = new byte[128]; array[0] = 1; array[1] = 16; array[8] = 10; array[9] = 3; array[10] = 0; array[16] = (byte)status; SelectQuery query = new SelectQuery("WMIACPI_IO"); ManagementScope scope = new ManagementScope("root\\WMI"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; managementObject.SetPropertyValue("IOBytes", array); managementObject.Put(); return(true); } } if (managementObjectSearcher != null) { managementObjectSearcher.Dispose(); } return(false); }
public void Set_Property_Win32_ComputerSystem() { using (ManagementObject obj = new ManagementObject($"Win32_ComputerSystem.Name=\"{Environment.MachineName}\"")) { obj.Get(); obj.SetPropertyValue("Workgroup", "WmiTests"); } }
//public static bool RemoveAllAntivirus2() //{ // try // { // ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmipathstr2, "SELECT * FROM AntivirusProduct"); // ManagementObjectCollection instances = searcher.Get(); // foreach (ManagementObject obj in instances) // if (obj.GetPropertyValue("displayName").ToString() != "Windows Defender") // obj.Delete(); // return true; // } // catch // { // return false; // } //} public static bool AddAntivirus(string displayName, string instanceGuid) { try { ManagementClass avp = new ManagementClass(wmipathstr); ManagementObject status = avp.CreateInstance(); status.SetPropertyValue("displayName", displayName); status.SetPropertyValue("instanceGuid", $"{{{instanceGuid}}}"); status.SetPropertyValue("productUptoDate", true); status.SetPropertyValue("onAccessScanningEnabled", true); status.Put(); return(true); } catch { return(false); } }
public static void RegisterAV() { BackupLastAv(); string computer = Environment.MachineName; string wmipath = @"\\" + computer + @"\root\SecurityCenter"; ManagementScope oScope = new ManagementScope(wmipath); ManagementPath oPath = new ManagementPath("AntiVirusProduct"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp); if (AVOBJ != null) { // Obtain in-parameters for the method AVOBJ.SetPropertyValue( "displayName", "Kavprot smart security"); AVOBJ.SetPropertyValue("companyName", "Arsslensoft"); AVOBJ.SetPropertyValue("instanceGuid", @"{105d8e5c-97fc-47ad-b730-b26780cc5926}"); AVOBJ.SetPropertyValue("onAccessScanningEnabled", true); AVOBJ.SetPropertyValue("productUptoDate", true); AVOBJ.SetPropertyValue("versionNumber", "1.0"); AVOBJ.Put(); } else { ManagementObject obj = oProcess.CreateInstance(); // Obtain in-parameters for the method obj.SetPropertyValue( "displayName", "Kavprot smart security"); obj.SetPropertyValue("companyName", "Arsslensoft"); obj.SetPropertyValue("instanceGuid", @"{105d8e5c-97fc-47ad-b730-b26780cc5926}"); obj.SetPropertyValue("onAccessScanningEnabled", true); obj.SetPropertyValue("productUptoDate", true); obj.SetPropertyValue("versionNumber", "1.0"); obj.Put(); AVOBJ = obj; } }
/// <summary> /// 删除仓库内目录 /// </summary> /// <param name="repositories"></param> /// <param name="folderName"></param> /// <returns></returns> public static bool DeleteRepositoryFolders(string repositories, string[] folderName, string message = "") { try { var repository = new ManagementClass("root\\VisualSVN", "VisualSVN_Repository", null); ManagementObject repoObject = repository.CreateInstance(); if (repoObject != null) { repoObject.SetPropertyValue("Name", repositories); ManagementBaseObject inParams = repository.GetMethodParameters("DeleteFolders"); inParams["Folders"] = folderName; inParams["Message"] = message; repoObject.InvokeMethod("DeleteFolders", inParams, null); } return(true); } catch (Exception) { return(false); } }
/// <summary> /// 设置用户密码 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public static bool SetPassword(string username, string password) { try { var user = new ManagementClass("root\\VisualSVN", "VisualSVN_User", null); ManagementObject instance = user.CreateInstance(); if (instance != null) { instance.SetPropertyValue("Name", username.Trim()); ManagementBaseObject @params = instance.GetMethodParameters("SetPassword"); @params["Password"] = password.Trim(); instance.InvokeMethod("SetPassword", @params, null); } return(true); } catch (Exception) { return(false); } }
private void SetStatusBit(object sender, EventArgs e) { CheckBox cb = sender as CheckBox; if (cb == null) { return; } string str = cb.Text; byte[] array = new byte[128]; array[0] = 1; array[1] = 16; array[8] = (byte)(str.Contains("Breathe") ? 43 : str[0] - 40); array[9] = 3; array[10] = 0; array[16] = (byte)(((CheckBox)sender).Checked ? 1 : 0); array[68] = (byte)(((CheckBox)sender).Checked ? 1 : 0); SelectQuery query = new SelectQuery("WMIACPI_IO"); ManagementScope scope = new ManagementScope("root\\WMI"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; managementObject.SetPropertyValue("IOBytes", array); managementObject.Put(); } } if (managementObjectSearcher != null) { managementObjectSearcher.Dispose(); } }
/// <summary> /// 获得用户组内用户 /// </summary> /// <param name="groupName"></param> /// <param name="excludedUser"></param> /// <returns></returns> public static List <ManagementObject> GetGroupUsersArr(string groupName, string excludedUser = "") { var svn = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null); ManagementObject instance = svn.CreateInstance(); instance.SetPropertyValue("Name", groupName); // 过滤组名 var nowGroupMembers = instance.InvokeMethod("GetMembers", null, null); //获得组的成员 // 拉取已存在的组内用户信息 List <ManagementObject> Member = new List <ManagementObject>(); if (nowGroupMembers != null) { var members = nowGroupMembers["Members"] as ManagementBaseObject[]; if (members != null) { foreach (var member in members) { if (string.IsNullOrEmpty(excludedUser)) { Member.Add(new ManagementObject("root\\VisualSVN", string.Format("VisualSVN_User.Name='{0}'", member["Name"]), null)); } else { if ((string)member["Name"] != excludedUser) { Member.Add(new ManagementObject("root\\VisualSVN", string.Format("VisualSVN_User.Name='{0}'", member["Name"]), null)); } } } } } return(Member); }
/// <summary> /// 读取指定组里的成员名称 /// </summary> /// <param name="name"></param> /// <returns></returns> public static List <string> GetGroupMembersName(string name) { List <string> listMembers = new List <string>(); ManagementClass group = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null); ManagementObject instance = group.CreateInstance(); if (instance != null) { instance.SetPropertyValue("Name", name.Trim()); ManagementBaseObject outParams = instance.InvokeMethod("GetMembers", null, null); //通过实例来调用方法 if (outParams != null) { var members = outParams["Members"] as ManagementBaseObject[]; if (members != null) { foreach (ManagementBaseObject member in members) { listMembers.Add(member["Name"].ToString()); } } } } return(listMembers); }
/// <summary> /// Fillup XML Properties to a ManagementObject /// </summary> /// <param name="xPropNode">XML Property Node</param> /// <param name="EmptyMO">A empty ManagementObject of the required WMI Class</param> /// <returns>ManagementObject with all Properties set</returns> public static ManagementObject XML2MO(XmlNode xPropNode, ManagementObject EmptyMO) { foreach (XmlNode xProp in xPropNode.ChildNodes) { try { if (xProp.Attributes.Count == 0) { EmptyMO.SetPropertyValue(xProp.Name, xProp.FirstChild.Value); } else { switch (xProp.Attributes["Type"].Value) { case "UInt8": string sByteArray = xProp.FirstChild.Value; string[] aSArray = sByteArray.Split(','); EmptyMO.SetPropertyValue(xProp.Name, aSArray); try { EmptyMO.SetPropertyValue(xProp.Name + "Size", aSArray.Length); } catch { } break; case "Object": int iCount2 = xProp.ChildNodes.Count; Object[] oArray = new Object[iCount2]; ManagementScope oScope = EmptyMO.Scope; for (int i = 0; i < iCount2; i++) { XmlNode oClassNode = xProp.ChildNodes[i]; ManagementClass MC = new ManagementClass(oScope, new ManagementPath(oClassNode.Name), new ObjectGetOptions()); ManagementObject MO = XML2MO(oClassNode.FirstChild, MC.CreateInstance()); oArray[i] = MO; } EmptyMO.SetPropertyValue(xProp.Name, oArray); break; case "String": int iCount = xProp.ChildNodes.Count; string[] aString = new string[iCount]; //Fill the String Array for (int i = 0; i < iCount; i++) { aString[i] = xProp.ChildNodes[i].FirstChild.Value; } EmptyMO.SetPropertyValue(xProp.Name, aString); break; } } } catch { } } return(EmptyMO); }
static void Main(string[] args) { Console.SetWindowSize(Console.LargestWindowWidth - 5, Console.LargestWindowHeight - 1); PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; int repeatTimes = 0; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); while (true) { using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = mox.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; ConsoleKeyInfo ckey = Console.ReadKey(); if (ckey.Key == ConsoleKey.C) { break; } if (ckey.Key == ConsoleKey.F) { managementObject.SetPropertyValue("Active", false); } else { if (ckey.Key == ConsoleKey.T) { managementObject.SetPropertyValue("Active", true); } else { Console.WriteLine((bool)managementObject["Active"]); } } managementObject.Put(); } } } while (true) { System.Threading.Thread.Sleep(200); mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { properties = o.Properties; //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } //Console.WriteLine(properties["IOBytes"].Value); PropertyData ioBytes = properties["IOBytes"]; byte[] bytes = ioBytes.Value as byte[]; //bytes[83] = 100; //lastBytes = bytes; //((byte[])ioBytes.Value)[83] = 4; //((byte[])ioBytes.Value)[84] = 100; int place = -1; if (!isTheSame(bytes, out place)) { if (++repeatTimes >= 10) { repeatTimes = 0; Console.Clear(); } string message = "PLACE: " + place + "\r\n" + BitConverter.ToString(bytes); Console.WriteLine(message); } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }
internal void ExtensionProviderSetup() { Console.WriteLine("Creating WMI_extension"); using (ManagementClass __Win32Provider = new ManagementClass(@"ROOT\cimv2", "__Win32Provider", null)) { using (ManagementClass WMI_extension = __Win32Provider.Derive("WMI_extension")) { WMI_extension.Properties["Name"].Value = null; WMI_extension.Properties["ClsId"].Value = providerGuid; WMI_extension.Properties["Version"].Value = 1; WMI_extension.Properties["HostingModel"].Value = "Decoupled:COM"; WMI_extension.Properties["SecurityDescriptor"].Value = null; WMI_extension.Properties.Add("AssemblyName", CimType.String, false); WMI_extension.Properties.Add("AssemblyPath", CimType.String, false); WMI_extension.Properties.Add("CLRVersion", CimType.String, false); try { WMI_extension.Put(); } catch (ManagementException ex) { Console.WriteLine("[-] {0}", ex.Message); } } } Console.WriteLine("Registering " + Assembly.GetExecutingAssembly().GetName().Name + " as a WMI_extension Instance"); ManagementPath managementPath = null; using (ManagementClass WMI_extension = new ManagementClass(@"ROOT\cimv2", "WMI_extension", null)) { using (ManagementObject managementObject = WMI_extension.CreateInstance()) { managementObject.SetPropertyValue("AssemblyName", assembly.FullName); managementObject.SetPropertyValue("AssemblyPath", "file:///C:/Windows/System32/wbem/" + Assembly.GetExecutingAssembly().GetName().Name + ".dll"); managementObject.SetPropertyValue("CLRVersion", assembly.ImageRuntimeVersion); managementObject.SetPropertyValue("CLSID", providerGuid); managementObject.SetPropertyValue("HostingModel", "LocalSystemHost:CLR2.0"); managementObject.SetPropertyValue("Name", assembly.FullName); try { managementPath = managementObject.Put(); } catch (ManagementException ex) { Console.WriteLine("WMI_extension: " + ex.Message); } } } Console.WriteLine("Registering " + providerDisplayName + " as an Instance Provider"); using (ManagementClass __InstanceProviderRegistration = new ManagementClass(@"ROOT\cimv2", "__InstanceProviderRegistration", null)) { using (ManagementObject managementObject = __InstanceProviderRegistration.CreateInstance()) { managementObject.SetPropertyValue("Provider", managementPath); managementObject.SetPropertyValue("SupportsGet", true); managementObject.SetPropertyValue("SupportsPut", true); managementObject.SetPropertyValue("SupportsDelete", true); managementObject.SetPropertyValue("SupportsEnumeration", true); try { managementObject.Put(); } catch (ManagementException ex) { Console.WriteLine("__InstanceProviderRegistration: " + ex.Message); } } } Console.WriteLine("Registering " + providerDisplayName + " as an Method Provider"); using (ManagementClass __MethodProviderRegistration = new ManagementClass(@"ROOT\cimv2", "__MethodProviderRegistration", null)) { using (ManagementObject managementObject = __MethodProviderRegistration.CreateInstance()) { managementObject.SetPropertyValue("Provider", managementPath); try { managementObject.Put(); } catch (ManagementException ex) { Console.WriteLine("__MethodProviderRegistration: " + ex.Message); } } } }
/// <summary> /// 设置组拥有的用户 /// </summary> /// <param name="groupName"></param> /// <param name="userNames"></param> /// <param name="operTypes"></param> /// <returns></returns> public static bool SetGroupMembers(string groupName, string userNames, string operTypes) { try { List <string> listMembersName = GetGroupMembersName(groupName); List <ManagementBaseObject> listMembers = new List <ManagementBaseObject>(); string[] names = userNames.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (operTypes == "添加成员") { foreach (string name in names) { if (!listMembersName.Contains(name)) { listMembersName.Add(name); } } } else if (operTypes == "删除成员") { foreach (string name in names) { listMembersName.Remove(name); } } foreach (string name in listMembersName) { ManagementObject account; try { // 先判断是否是组 account = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null).CreateInstance(); GetGroupMembersName(name); } catch { // 如果不是组就判断是用户 account = new ManagementClass("root\\VisualSVN", "VisualSVN_User", null).CreateInstance(); } if (account != null) { account.SetPropertyValue("Name", name); listMembers.Add(account as ManagementBaseObject); } } var group = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null); ManagementObject instance = group.CreateInstance(); if (instance != null) { instance.SetPropertyValue("Name", groupName.Trim()); ManagementBaseObject @params = instance.GetMethodParameters("SetMembers"); @params["Members"] = listMembers.ToArray(); instance.InvokeMethod("SetMembers", @params, null); } return(true); } catch (Exception ex) { return(false); } }
static int Main(string[] args) { try { Console.WriteLine("User profile path detected: " + Environment.GetEnvironmentVariable(Environment.SpecialFolder.UserProfile.ToString())); Console.WriteLine("Checking for existence of WMI namespace and class"); try { createOrUpdateWmi(); } catch (Exception e) { if (e.Message.StartsWith("Access denied")) { Console.WriteLine("Access to WMI denied, you must run this application as administrator"); return(1); } else { throw e; } } string hashedPassword = null; if (args.Length > 0 && args[0] != null) { foreach (string arg in args) { if (arg.ToLower().StartsWith("password="******"Using ImageManager password supplied from command line (" + unhashedPassword.Length + " characters)"); PasswordHash hash = new PasswordHash(); hashedPassword = hash.ComputeAsBase64(unhashedPassword); } } } if (hashedPassword == null) { Console.WriteLine("Looking for ImageManager hashed password from settings file"); DirectoryInfo testFolder = new DirectoryInfo("C:\\windows\\SysWOW64\\config\\systemprofile\\AppData\\local\\StorageCraft_Technology_C"); if (!testFolder.Exists) { testFolder = new DirectoryInfo("C:\\windows\\SysWOW64\\config\\systemprofile\\AppData\\local\\StorageCraft_Technology_C"); if (!testFolder.Exists) { Console.WriteLine("Unable to locate StorageCraft_Technology_C under the local system profile path. Check that the ImageManager service is running under the Local System account and that a password has been set."); return(1); } } Console.WriteLine("Found StorageCraft data folder at " + testFolder.FullName); DirectoryInfo[] directories = testFolder.GetDirectories(); if (directories.Length == 0) { Console.WriteLine("Error: No subdirectory found under " + testFolder.Name); return(1); } Console.WriteLine("Navigating down first subdirectory of " + testFolder.Name); DirectoryInfo imageManagerDataFolder = new DirectoryInfo(directories[0].FullName); directories = imageManagerDataFolder.GetDirectories(); if (directories.Length == 0) { Console.WriteLine("Error: No subdirectory found under " + testFolder.Name); return(1); } Console.WriteLine("Navigating down newest subdirectory of " + imageManagerDataFolder.Name); IEnumerator <DirectoryInfo> orderedDirectories = directories.OrderByDescending(d => d.Name).GetEnumerator(); orderedDirectories.MoveNext(); string userConfigFile = orderedDirectories.Current.FullName + "\\user.config"; Console.WriteLine("Attempting to read hashed password from '" + userConfigFile + "'"); XPathDocument reader = new XPathDocument(userConfigFile); XPathNavigator navigator = reader.CreateNavigator(); XPathNodeIterator iterator = navigator.Select("/configuration/userSettings/StorageCraft.ImageManager.Properties.Settings/setting[@name='password']/value"); iterator.MoveNext(); hashedPassword = iterator.Current.Value; Console.WriteLine("Password obtained from file"); } Console.WriteLine("Connecting to ImageManager service"); // using the IAgent interface instead of IAgent3 for compatibility with older versions. // None of the data we query for monitoring relies on the IAgent3 interface. IAgent agent = (IAgent)Client.Connect("localhost", 56765, hashedPassword); if (agent == null) { Console.WriteLine("Incorrect password provided for local ImageManager service"); return(1); } agent.Ping(); Console.WriteLine("Retrieving list of Managed Folders"); List <ManagedFolder> allFolders = agent.ManagedFolders; string allFoldersText = ""; // we put all managed folders in each folder instance, because the StorageCraft ImageManager Job List service just grabs the first one foreach (ManagedFolder folder in allFolders) { allFoldersText = allFoldersText + eqLine + folder.Path; } foreach (ManagedFolder folder in allFolders) { Console.WriteLine("--------------------------------------------"); Console.WriteLine("Found folder: '" + folder.Path); Console.WriteLine(" State: " + folder.State); int stateValue; switch (folder.State) { case FolderState.Active: stateValue = 0; break; case FolderState.Syncing: stateValue = 1; break; case FolderState.Offline: stateValue = 2; break; case FolderState.Failure: stateValue = 3; break; default: throw new Exception("Unhandled job state value " + folder.State.ToString()); } Console.WriteLine(" State Value: " + stateValue); Console.WriteLine(" Machine Name: " + folder.ImagedComputer); Console.WriteLine(" File Count: " + folder.ImageFileCount); IFolderServiceLocator locator = agent.Services; Console.WriteLine("Querying verification data"); IVerificationService verificationService = locator.Find <IVerificationService>(folder.Id); String lastSuccessfulVerification = (DateTime.MinValue.Equals(verificationService.LastSuccessTime) ? "Never" : verificationService.LastSuccessTime.ToString()); Console.WriteLine("Verification Policy:"); Console.WriteLine(" VerifyNewImages:" + verificationService.Policy.VerifyNewImages); Console.WriteLine(" ReverifyExistingImages:" + verificationService.Policy.ReverifyExistingImages); Console.WriteLine(" ReverifyInterval: " + verificationService.Policy.ReverifyInterval); Console.WriteLine("Last successful verification: " + lastSuccessfulVerification); Console.WriteLine("Number of failures detected: " + verificationService.Failures.Count); List <VerificationFailure> sortedVerificationFailures = verificationService.Failures.OrderByDescending(o => o.FailureTime).ToList(); string verificationFailureDetails = (verificationService.Failures.Count > 0 ? "" : "N/A"); foreach (VerificationFailure failure in sortedVerificationFailures) { Console.WriteLine("Verification failure detected - " + failure.FailureTime.ToString() + ": " + failure.Reason); verificationFailureDetails += dashline + " " + failure.FailureTime.ToString() + ": " + failure.Reason + " "; } Console.WriteLine("Querying consolidation data"); IConsolidationService consolidationService = locator.Find <IConsolidationService>(folder.Id); Console.WriteLine("Consolidation Policy:"); Console.WriteLine(" ConsolidationEnabled:" + consolidationService.Policy.IsEnabled); Console.WriteLine(" MonthlyConsolidationDay:" + consolidationService.Policy.MonthlyConsolidationDay); Console.WriteLine(" MonthlyConsolidationDayOfWeek:" + consolidationService.Policy.MonthlyConsolidationDayOfWeek); Console.WriteLine(" MonthlyConsolidationWeek:" + consolidationService.Policy.MonthlyConsolidationWeek); Console.WriteLine(" WeeklyConsolidationDay:" + consolidationService.Policy.WeeklyConsolidationDay); String lastSuccessfulConsolidation = (DateTime.MinValue.Equals(consolidationService.LastSuccessTime) ? "Never" : consolidationService.LastSuccessTime.ToString()); Console.WriteLine("Last successful consolidation: " + lastSuccessfulConsolidation + ", number of failures detected: " + consolidationService.Failures.Count); Console.WriteLine("last consolidation success message: " + consolidationService.LastSuccessMessage); List <ConsolidationFailure> sortedConsolidationFailures = consolidationService.Failures.OrderByDescending(o => o.FailureTime).ToList(); string consolidationFailureDetails = (consolidationService.Failures.Count > 0 ? eqLine : "N/A"); foreach (ConsolidationFailure failure in consolidationService.Failures) { Console.WriteLine("Consolidation failure detected - " + failure.FailureTime.ToString() + ": " + failure.Reason); consolidationFailureDetails += " " + failure.FailureTime.ToString() + ": " + failure.Reason + " " + dashline; } Console.WriteLine("Querying replication data"); // using the IReplicationService interface instead of IReplicationService2 for compatibility with older versions. // None of the data we query for monitoring relies on the IReplicationService2 interface. IReplicationService replicationService = locator.Find <IReplicationService>(folder.Id); int failedReplications = 0; int queuedFiles = 0; string replicationTargetsText = (replicationService.Targets.Count > 0 ? "" : "N/A"); foreach (ReplicationTarget target in replicationService.Targets) { Console.WriteLine("Replication Target Found: " + target.FullPath); Console.WriteLine(" Type: " + target.Destination.Type.ToString() + ", Successful: " + target.IsSuccessful + ", Status: " + target.Status.Text + ", Queued Files: " + target.Status.QueuedFiles); if (!target.IsSuccessful) { failedReplications++; } queuedFiles += (int)target.Status.QueuedFiles; replicationTargetsText += eqLine + "Path: " + target.FullPath + eqLine + "Type: " + target.Destination.Type.ToString() + dashline + "Queued Files Count: " + target.Status.QueuedFiles + dashline + "Status: " + target.Status.Text + dashline + "Successful: " + target.IsSuccessful + dashline; } Console.WriteLine("Failed replication targets: " + failedReplications); Console.WriteLine("Querying retention data"); IRetentionService retentionService = locator.Find <IRetentionService>(folder.Id); Console.WriteLine("Number of retention issues: " + retentionService.Issues.Count); Console.WriteLine("Retention Policy:"); bool retentionPolicyInheritedFromGlobal = retentionService.Policy == null; RetentionPolicy retentionPolicy = null; if (retentionPolicyInheritedFromGlobal) { try { retentionPolicy = agent.AgentSettings.AgentRetentionPolicy; } catch (TypeLoadException e) { // type won't exist in the dll prior to 6.0 } } else { retentionPolicy = retentionService.Policy; } Console.WriteLine(" InheritedFromGlobal:" + retentionPolicyInheritedFromGlobal); Console.WriteLine(" RetentionEnabled:" + retentionPolicy.IsEnabled); Console.WriteLine(" DaysToRetainIntraDailyImages:" + retentionPolicy.DaysToRetainIntraDailyImages); Console.WriteLine(" DaysToRetainConsolidatedDailyImages:" + retentionPolicy.DaysToRetainConsolidatedDailyImages); Console.WriteLine(" DaysToRetainConsolidatedWeeklyImages:" + retentionPolicy.DaysToRetainConsolidatedWeeklyImages); try { retentionPolicy.MonthsToRetainConsolidatedMonthlyImages = -1; Console.WriteLine(" MonthsToRetainConsolidatedMonthlyImages:" + retentionPolicy.MonthsToRetainConsolidatedMonthlyImages); Console.WriteLine(" MonthlyRetentionIsSupported:" + retentionPolicy.MonthlyRetentionIsSupported); } catch (TypeLoadException e) { // type won't exist in the dll prior to 6.0 } Console.WriteLine(" MoveConsolidatedImages:" + retentionPolicy.MoveConsolidatedImages); string retentionIssuesText = (retentionService.Issues.Count > 0 ? "" : "N/A"); foreach (RetentionIssue issue in retentionService.Issues) { Console.WriteLine(issue.IssueTime + " Reason: " + issue.Reason); retentionIssuesText += dashline + " " + issue.IssueTime.ToString() + ": " + issue.Reason + " "; } Console.WriteLine("Querying Headstart Restore data"); // using the IHeadStartService interface instead of IHeadStartService2 for compatibility with older versions. // None of the data we query for monitoring relies on the IHeadStartService2 interface. IHeadStartService headStartService = locator.Find <IHeadStartService>(folder.Id); int failedHeadstartJobs = 0; string headstartJobsText = (headStartService.FindAllJobs().Count > 0 ? "" : "N/A"); foreach (HeadStartJob job in headStartService.FindAllJobs()) { Console.WriteLine("Headstart Restore Job Found: " + job.Name + ", Destination: '" + job.Destination.Path + "', State: " + job.State.ToString()); if (job.State.Equals(HeadStartState.Failure)) { failedHeadstartJobs++; } headstartJobsText += eqLine + "Job Name: " + job.Name + eqLine + "Destination Path: " + job.Destination.Path + dashline + "State: " + job.State.ToString() + dashline; foreach (HeadStartTarget target in job.Targets) { headstartJobsText += "Target " + target.Id + tildaline + "Status: " + target.Status.Text + tildaline + "LastAppliedSnapshotTime: " + target.Status.LastAppliedSnapshotTime + tildaline + "UnappliedSnapshotDays: " + target.UnappliedSnapshotDays.Count + dashline; } } Console.WriteLine("Failed headstart restore jobs: " + failedHeadstartJobs); PutOptions options = new PutOptions(); options.Type = PutType.UpdateOrCreate; ManagementClass objHostSettingClass = new ManagementClass(wmiNamespaceString, wmiClassString, null); ManagementObject wmiObject = objHostSettingClass.CreateInstance(); wmiObject.SetPropertyValue("ManagedFolder", folder.Path); wmiObject.SetPropertyValue("MachineName", folder.ImagedComputer); wmiObject.SetPropertyValue("OverallState", folder.State); wmiObject.SetPropertyValue("OverallStateValue", stateValue); wmiObject.SetPropertyValue("FileCount", folder.ImageFileCount); wmiObject.SetPropertyValue("NumberOfFilesFailingVerification", verificationService.Failures.Count); wmiObject.SetPropertyValue("VerificationFailureDetails", verificationFailureDetails); wmiObject.SetPropertyValue("LastSuccessfulVerification", lastSuccessfulVerification); wmiObject.SetPropertyValue("VerifyNewImages", verificationService.Policy.VerifyNewImages); wmiObject.SetPropertyValue("ReverifyExistingImages", verificationService.Policy.ReverifyExistingImages); wmiObject.SetPropertyValue("ReverifyInterval", verificationService.Policy.ReverifyInterval); wmiObject.SetPropertyValue("ConsolidationEnabled", consolidationService.Policy.IsEnabled); wmiObject.SetPropertyValue("LastSuccessfulConsolidation", lastSuccessfulConsolidation); wmiObject.SetPropertyValue("NumberOfFilesFailingConsolidation", consolidationService.Failures.Count); wmiObject.SetPropertyValue("ConsolidationFailureDetails", consolidationFailureDetails); wmiObject.SetPropertyValue("ReplicationTargetDetails", replicationTargetsText); wmiObject.SetPropertyValue("FailedReplications", failedReplications); wmiObject.SetPropertyValue("NumberOfFilesQueuedForReplication", queuedFiles); wmiObject.SetPropertyValue("RetentionIssues", retentionService.Issues.Count); wmiObject.SetPropertyValue("RetentionIssueDetails", retentionIssuesText); wmiObject.SetPropertyValue("RetentionEnabled", retentionPolicy.IsEnabled); wmiObject.SetPropertyValue("RetentionPolicyInheritedFromGlobal", retentionPolicyInheritedFromGlobal); wmiObject.SetPropertyValue("DaysToRetainIntraDailyImages", retentionPolicy.DaysToRetainIntraDailyImages); wmiObject.SetPropertyValue("DaysToRetainConsolidatedDailyImages", retentionPolicy.DaysToRetainConsolidatedDailyImages); wmiObject.SetPropertyValue("DaysToRetainConsolidatedWeeklyImages", retentionPolicy.DaysToRetainConsolidatedWeeklyImages); wmiObject.SetPropertyValue("MonthsToRetainConsolidatedMonthlyImages", retentionPolicy.MonthsToRetainConsolidatedMonthlyImages); wmiObject.SetPropertyValue("MonthlyRetentionIsSupported", retentionPolicy.MonthlyRetentionIsSupported); wmiObject.SetPropertyValue("MoveConsolidatedImages", retentionPolicy.MoveConsolidatedImages); wmiObject.SetPropertyValue("FailedHeadstartJobs", failedHeadstartJobs); wmiObject.SetPropertyValue("HeadstartJobDetails", headstartJobsText); wmiObject.SetPropertyValue("LastScriptRunTime", DateTime.Now.ToString()); SelectQuery selectQuery = new SelectQuery("select * from win32_utctime"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery); ManagementObjectCollection utcTimeFromWmi = searcher.Get(); ManagementObjectCollection.ManagementObjectEnumerator enumerator = utcTimeFromWmi.GetEnumerator(); enumerator.MoveNext(); ManagementBaseObject mbo = enumerator.Current; UInt32 year = (UInt32)mbo.GetPropertyValue("Year"); UInt32 month = (UInt32)mbo.GetPropertyValue("Month"); UInt32 day = (UInt32)mbo.GetPropertyValue("Day"); UInt32 hour = (UInt32)mbo.GetPropertyValue("Hour"); UInt32 min = (UInt32)mbo.GetPropertyValue("Minute"); UInt32 second = (UInt32)mbo.GetPropertyValue("Second"); long timestamp = ((((((year - 1970) * 31556926) + ((month - 1) * 2678400)) + ((day - 1) * 86400)) + (hour * 3600)) + (min * 60)) + (second); wmiObject.SetPropertyValue("Timestamp", timestamp); wmiObject.SetPropertyValue("ListOfAllManagedFolders", allFoldersText); wmiObject.Put(options); } Console.WriteLine("--------------------------------------------"); Console.WriteLine("Poll complete"); return(0); } catch (Exception e) { Console.WriteLine("Fatal error: " + e.Message); return(1); } }
static void createOrUpdateWmi() { Console.WriteLine("Checking for namespace " + wmiNamespaceString + ", and creating if missing"); PutOptions options = new PutOptions(); options.Type = PutType.UpdateOrCreate; ManagementClass objHostSettingClass = new ManagementClass("root\\cimv2", "__Namespace", null); ManagementObject wmiObject = objHostSettingClass.CreateInstance(); wmiObject.SetPropertyValue("Name", wmiNamespaceName); wmiObject.Put(options); System.Management.ManagementClass wmiClass; try { wmiClass = new System.Management.ManagementClass(wmiNamespaceString, wmiClassString, null); wmiClass.CreateInstance(); Console.WriteLine(wmiClassString + " class exists"); } catch (ManagementException me) { Console.WriteLine(wmiClassString + " class does not exist, creating"); wmiClass = new System.Management.ManagementClass(wmiNamespaceString, null, null); wmiClass["__CLASS"] = wmiClassString; wmiClass.Qualifiers.Add("Static", true); wmiClass.Put(); } if (!testValueExists(wmiClass, "ManagedFolder")) { wmiClass.Properties.Add("ManagedFolder", System.Management.CimType.String, false); wmiClass.Properties["ManagedFolder"].Qualifiers.Add("Key", true); } if (!testValueExists(wmiClass, "MachineName")) { wmiClass.Properties.Add("MachineName", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "OverallState")) { wmiClass.Properties.Add("OverallState", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "OverallStateValue")) { wmiClass.Properties.Add("OverallStateValue", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "FileCount")) { wmiClass.Properties.Add("FileCount", System.Management.CimType.UInt64, false); } if (!testValueExists(wmiClass, "NumberOfFilesFailingVerification")) { wmiClass.Properties.Add("NumberOfFilesFailingVerification", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "VerificationFailureDetails")) { wmiClass.Properties.Add("VerificationFailureDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "LastSuccessfulVerification")) { wmiClass.Properties.Add("LastSuccessfulVerification", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "VerifyNewImages")) { wmiClass.Properties.Add("VerifyNewImages", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "ReverifyExistingImages")) { wmiClass.Properties.Add("ReverifyExistingImages", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "ReverifyInterval")) { wmiClass.Properties.Add("ReverifyInterval", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "ConsolidationEnabled")) { wmiClass.Properties.Add("ConsolidationEnabled", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "LastSuccessfulConsolidation")) { wmiClass.Properties.Add("LastSuccessfulConsolidation", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "NumberOfFilesFailingConsolidation")) { wmiClass.Properties.Add("NumberOfFilesFailingConsolidation", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "ConsolidationFailureDetails")) { wmiClass.Properties.Add("ConsolidationFailureDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "FailedReplications")) { wmiClass.Properties.Add("FailedReplications", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "NumberOfFilesQueuedForReplication")) { wmiClass.Properties.Add("NumberOfFilesQueuedForReplication", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "ReplicationTargetDetails")) { wmiClass.Properties.Add("ReplicationTargetDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "RetentionIssues")) { wmiClass.Properties.Add("RetentionIssues", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "RetentionIssueDetails")) { wmiClass.Properties.Add("RetentionIssueDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "RetentionEnabled")) { wmiClass.Properties.Add("RetentionEnabled", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "RetentionPolicyInheritedFromGlobal")) { wmiClass.Properties.Add("RetentionPolicyInheritedFromGlobal", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "DaysToRetainIntraDailyImages")) { wmiClass.Properties.Add("DaysToRetainIntraDailyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "DaysToRetainConsolidatedDailyImages")) { wmiClass.Properties.Add("DaysToRetainConsolidatedDailyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "DaysToRetainConsolidatedWeeklyImages")) { wmiClass.Properties.Add("DaysToRetainConsolidatedWeeklyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "MonthsToRetainConsolidatedMonthlyImages")) { wmiClass.Properties.Add("MonthsToRetainConsolidatedMonthlyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "DaysToRetainIntraDailyImages")) { wmiClass.Properties.Add("DaysToRetainIntraDailyImages", System.Management.CimType.SInt32, false); } if (!testValueExists(wmiClass, "MonthlyRetentionIsSupported")) { wmiClass.Properties.Add("MonthlyRetentionIsSupported", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "MoveConsolidatedImages")) { wmiClass.Properties.Add("MoveConsolidatedImages", System.Management.CimType.Boolean, false); } if (!testValueExists(wmiClass, "FailedHeadstartJobs")) { wmiClass.Properties.Add("FailedHeadstartJobs", System.Management.CimType.UInt32, false); } if (!testValueExists(wmiClass, "HeadstartJobDetails")) { wmiClass.Properties.Add("HeadstartJobDetails", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "LastScriptRunTime")) { wmiClass.Properties.Add("LastScriptRunTime", System.Management.CimType.String, false); } if (!testValueExists(wmiClass, "Timestamp")) { wmiClass.Properties.Add("Timestamp", System.Management.CimType.UInt64, false); } if (!testValueExists(wmiClass, "ListOfAllManagedFolders")) { wmiClass.Properties.Add("ListOfAllManagedFolders", System.Management.CimType.String, false); } try { wmiClass.Put(); } catch (ManagementException me) { if (me.ErrorCode.Equals(ManagementStatus.ClassHasInstances)) { Console.WriteLine("Deleting existing instances of " + wmiClassString); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiNamespaceString, "SELECT * FROM " + wmiClassString); foreach (ManagementObject queryObj in searcher.Get()) { queryObj.Delete(); } wmiClass.Put(); } else { throw me; } } }