public static bool AddNIC(this ManagementObject VM, string VirtualSwitch = null, bool Legacy = false) { // Sanity Check if (VM == null || !VM["__CLASS"].ToString().Equals(VMStrings.ComputerSystem, StringComparison.InvariantCultureIgnoreCase)) { return(false); } ManagementScope scope = GetScope(VM); ManagementObject NIC = VM.NewResource(ResourceTypes.EthernetAdapter, (Legacy ? ResourceSubTypes.LegacyNIC : ResourceSubTypes.SyntheticNIC), scope); NIC["ElementName"] = (Legacy ? "Legacy " : "") + "Network Adapter"; if (!Legacy) { NIC["VirtualSystemIdentifiers"] = new string[] { Guid.NewGuid().ToString("B") } } ; if (VirtualSwitch != null) { ManagementObject Switch = new ManagementObjectSearcher(scope, new SelectQuery(VMStrings.VirtualSwitch, "ElementName like '" + VirtualSwitch + "'")).Get().Cast <ManagementObject>().FirstOrDefault(); if (Switch == null) { NIC.Delete(); return(false); } string PortGUID = Guid.NewGuid().ToString(); ManagementObject SwitchSvc = GetServiceObject(scope, ServiceNames.SwitchManagement); var inputs = SwitchSvc.GetMethodParameters("CreateSwitchPort"); inputs["VirtualSwitch"] = Switch.Path.Path; inputs["Name"] = inputs["FriendlyName"] = PortGUID; inputs["ScopeOfResidence"] = String.Empty; var ret = SwitchSvc.InvokeMethod("CreateSwitchPort", inputs, null); if (int.Parse(ret["ReturnValue"].ToString()) != (int)ReturnCodes.OK) { NIC.Delete(); return(false); } NIC["Connection"] = new string[] { GetObject(ret["CreatedSwitchPort"].ToString()).Path.Path }; } return(VM.AddDevice(NIC) != null); }
/// <summary> /// Deletes an AppPool. /// </summary> /// <param name="name">The AppPool name.</param> /// <param name="machineName">The server on which the AppPool is running.</param> /// <param name="millisecondsTimeout">Timeout value on wait for Delete to complete.</param> /// <returns>The Wmi ManagementPath</returns> public static void Delete(string name, string machineName, int millisecondsTimeout) { ManagementOptions options = new DeleteOptions(); ManagementObject appPool = GetAppPoolManagementObject(name, machineName, millisecondsTimeout, ref options); appPool.Delete((DeleteOptions)options); }
private static void NewObject(object sender, ObjectReadyEventArgs args) { ManagementObject obj = (ManagementObject)args.NewObject; obj.Delete(); }
private void DeleteUserInternal(string instanceId) { HostedSolutionLog.LogStart("DeleteUserInternal"); try { if (string.IsNullOrEmpty(instanceId)) { throw new ArgumentException("instanceId"); } using (ManagementObject userObject = GetUserByInstanceId(instanceId)) { if (userObject == null) { HostedSolutionLog.LogWarning("OCS user {0} not found", instanceId); } else { userObject.Delete(); } } } catch (Exception ex) { HostedSolutionLog.LogError("DeleteUserInternal", ex); throw; } HostedSolutionLog.LogEnd("DeleteUserInternal"); }
public static void ClientAction(IResultObject resultObject) { try { if (fullScan) { ManagementScope scope = Utility.GetWMIScope(resultObject["Name"].StringValue, @"ccm\InvAgt"); ManagementObject result = Utility.GetFirstWMIInstance(scope, string.Format("SELECT * FROM InventoryActionStatus WHERE InventoryActionID = '{0}'", scheduleId)); if (result != null) { result.Delete(); } } ObjectGetOptions o = new ObjectGetOptions(null, TimeSpan.FromSeconds(5), true); using (ManagementClass clientaction = new ManagementClass(string.Format(@"\\{0}\root\ccm:SMS_Client", resultObject["Name"].StringValue), o)) { object[] methodArgs = { scheduleId }; clientaction.InvokeMethod("TriggerSchedule", methodArgs); } } catch (Exception) { throw; } }
private void RemoveCachedItems(ListView.SelectedListViewItemCollection items) { foreach (ListViewItem item in items) { try { // get the wmi object ManagementObject managementObject = (ManagementObject)item.Tag; // create location string string str = (managementObject["Location"] as string).Replace(':', '$'); string path = string.Format(@"\\{0}\{1}", PropertyManager["Name"].StringValue, str); // check if cached content exists and we have persmissions to remove it if (Directory.Exists(path) && Utility.CheckFolderPermissions(path, FileSystemRights.Delete)) { // delete folder Directory.Delete(path, true); // remove wmi object managementObject.Delete(); } else { System.Windows.MessageBox.Show(string.Format("Cannot remove item: Access denied", items.Count), "Configuration Manager", MessageBoxButton.OK, MessageBoxImage.Hand); } } catch (Exception ex) { log.Error(string.Format("{0}: {1}", ex.GetType().Name, ex.Message)); SccmExceptionDialog.ShowDialog(SnapIn.Console, ex); } } }
private void DeleteNamespace(ManagementObject config) { // Delete all child namespaces first. var searcher = new ManagementObjectSearcher(_scope, GetChildQuery(Constants.Wmi.Namespace.Class, config)); using (ManagementObjectCollection childConfigs = searcher.Get()) { foreach (ManagementObject childConfig in childConfigs) { DeleteNamespace(childConfig); } } // Delete sources. searcher = new ManagementObjectSearcher(_scope, GetChildQuery(Constants.Wmi.Source.Class, config)); using (ManagementObjectCollection childConfigs = searcher.Get()) { foreach (ManagementObject childConfig in childConfigs) { DeleteSource(childConfig); } } // Delete the namespace itself. config.Delete(); }
private void DeleteDomainInternal(string domainName) { HostedSolutionLog.LogStart("DeleteDomainInternal"); HostedSolutionLog.DebugInfo("Domain Name: {0}", domainName); try { if (string.IsNullOrEmpty(domainName)) { throw new ArgumentException("domainName"); } using (ManagementObject domainObj = GetDomain(domainName)) { if (domainObj == null) { HostedSolutionLog.LogWarning("OCS internal domain '{0}' not found", domainName); } else { domainObj.Delete(); } } } catch (Exception ex) { HostedSolutionLog.LogError("DeleteDomainInternal", ex); throw; } HostedSolutionLog.LogEnd("DeleteDomainInternal"); }
private void DeleteReceiveHandler(string adapterName, string serverName, string hostName, HandlerType handlerType) { try { string handler = handlerType == HandlerType.Receive ? "MSBTS_ReceiveHandler" : "MSBTS_SendHandler2"; string query = string.Format("Select * FROM {0} WHERE AdapterName=\"{1}\" AND HostName=\"{2}\"", handler, adapterName, hostName); ManagementObjectSearcher searcher = new ManagementObjectSearcher(new ManagementScope(string.Format(BIZTALKSCOPE, serverName)), new WqlObjectQuery(query), null); ManagementObjectCollection result = searcher.Get(); IEnumerator enumerator = result.GetEnumerator(); if (!enumerator.MoveNext()) { Console.WriteLine("Not found"); return; } ManagementObject o = (ManagementObject)enumerator.Current; o.Delete(); } catch (Exception ex) { throw new ApplicationException("Failed while deleting receive handler", ex); } }
public void DeleteVirtualDirectory(string subPath) { var name = String.Format(@"{0}/root/{1}", Name, subPath); var path = string.Format("IIsWebVirtualDir.Name='{0}'", name); var virtualDirectory = new ManagementObject(scope, new ManagementPath(path), null); virtualDirectory.Delete(); }
protected override void EndProcessing() { base.EndProcessing(); if (ShouldProcess(string.Format("{0} on server {1}", name, Computer))) { ManagementObject site = CreateClassInstance(Computer, "Site.Name=\"" + Name + "\""); site.Delete(); } }
private static void NewObject(object sender, ObjectReadyEventArgs args) { ManagementObject obj = (ManagementObject)args.NewObject; GetLogger().Info("LogCleaner: deleting file " + obj["Name"] + " with creation date " + ManagementDateTimeConverter.ToDateTime(obj["CreationDate"].ToString()) + "."); obj.Delete(); }
/// <summary> /// Removes the Resource from DNS /// </summary> public void Delete() { try { m_mo.Delete(); } catch (ManagementException me) { throw new WMIException(me); } }
public void Dispose() { var record = new ManagementObject(owner.scope, new ManagementPath(path), null); try { record.Delete(); } finally { record.Dispose(); } }
/// <summary> /// Deletes site /// </summary> /// <param name="siteId"></param> internal static void DeleteSite(string siteId) { try { ManagementObject objSite = wmi.GetObject(String.Format("IIsWebServer='{0}'", siteId)); objSite.Delete(); } catch (Exception ex) { throw new Exception("Can't delete web site", ex); } }
public void DeleteVirtualDirectory() { var siteId = 1574596940; // var siteId = 1; var dir = "iplayer"; var name = String.Format(@"W3SVC/{0}/root/{1}", siteId, dir); var path = string.Format("IIsWebVirtualDir.Name='{0}'", name); var app = new ManagementObject(Scope, new ManagementPath(path), null); app.Delete(); }
static Dialog BuildUninstallServiceDialog() { var cancel = new Button("Cancel"); cancel.Clicked += () => { Application.RequestStop(); }; Dialog dlg = new Dialog("Uninstall service", 50, 15, cancel) { Width = Dim.Percent(80), Height = Dim.Percent(80) }; ServiceController[] scServices; scServices = ServiceController.GetServices(); var jsdalLikeServices = scServices.Where(sc => sc.ServiceName.ToLower().Contains("jsdal")).ToList(); var items = jsdalLikeServices.Select(s => $"({s.Status}) {s.DisplayName}").ToArray(); dlg.Add(new Label(1, 1, "Select a jsdal service to uninstall:")); for (var i = 0; i < items.Length; i++) { var local = i; var but = new Button(1, 3 + i, items[i]); but.Clicked += () => { var service = jsdalLikeServices[local]; int ret = MessageBox.Query(80, 10, "Confirm action", $"Are you sure you want to uninstall '{service.ServiceName}'?", "Confirm", "Cancel"); if (ret == 0) { ManagementObject wmiService; wmiService = new ManagementObject("Win32_Service.Name='" + service.ServiceName + "'"); wmiService.Get(); wmiService.Delete(); MessageBox.Query(30, 8, "", "Service uninstalled", "Ok"); Application.RequestStop(); } else if (ret == 1) { } }; dlg.Add(but); } return(dlg); }
/// <summary> /// Unregister the app from WMI /// </summary> /// <exception cref="System.Exception">if unable to /// commit the new application setting in wmi /// </exception> public void Unregister() { try { appSetting.Delete(); } catch (Exception e) { ///ignore, can happen if class was not found Debug.Write(e.Message); } }
/// <summary> /// Deletes virtual directory /// </summary> /// <param name="siteId"></param> /// <param name="directoryName"></param> internal static void DeleteVirtualDirectory(string siteId, string directoryName) { try { ManagementObject objDir = wmi.GetObject(String.Format("IIsWebVirtualDir='{0}'", GetVirtualDirectoryPath(siteId, directoryName))); objDir.Delete(); } catch (Exception ex) { throw new Exception("Can't delete virtual directory", ex); } }
/// <summary> /// Deletes application pool /// </summary> /// <param name="name"></param> internal static void DeleteApplicationPool(string name) { try { ManagementObject objPool = wmi.GetObject(String.Format("IIsApplicationPool='W3SVC/AppPools/{0}'", name)); objPool.Delete(); } catch (Exception ex) { throw new Exception("Can't delete application pool", ex); } }
public static void DeleteUserProfile(string userName) { #region Удаляем профиль пользователя PrintMessage(String.Format("{0:T} Удаляем профиль пользователя с именем {1}", DateTime.Now, userName), Type.information); ManagementObject user = null; SelectQuery query = new SelectQuery("Select * from win32_userprofile"); ManagementObjectSearcher searcher = null; try { searcher = new ManagementObjectSearcher(query); foreach (ManagementObject userProfile in searcher.Get()) { if (userProfile["localpath"].ToString().ToLower() == "c:\\users\\" + userName.ToLower()) { user = userProfile; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } if (user != null) { try { user.Delete(); PrintMessage(String.Format("Профиль пользователя {0} успешно удален", userName), Type.success); } catch (Exception ex) { PrintMessage(String.Format("Произошла ошибка при удалении профиля пользователя {0}" + ex.Message, userName), Type.error); } } else { PrintMessage(String.Format("Не найден профиль пользователя с именем {0}", userName), Type.error); } Console.WriteLine("Список профилей пользователей:"); foreach (ManagementObject userProfile in searcher.Get()) { Console.WriteLine("\t" + userProfile["localpath"]); } Console.WriteLine(); #endregion }
public static void delete_consumer(string target, string consumerName) { ManagementScope scope = getScope(target, true); ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null); ManagementObject filter = wmiEventFilter.CreateInstance(); filter["Name"] = consumerName + "Filter"; filter.Delete(); ManagementObject consumer = new ManagementClass(scope, new ManagementPath("LogFileEventConsumer"), null).CreateInstance(); consumer["Name"] = consumerName + "Consumer"; consumer.Delete(); }
public void imethod_0(HashSet <string> hashSet_0 = null) { ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\standardcimv2"); new ManagementClass(scope, new ManagementPath("MSFT_NetIPAddress"), new ObjectGetOptions()); foreach (ManagementBaseObject managementBaseObject in new ManagementObjectSearcher(scope, new ObjectQuery("SELECT * FROM MSFT_NetIPAddress")).Get()) { ManagementObject managementObject = (ManagementObject)managementBaseObject; string item = GClass885.smethod_0 <string>(managementObject, "IPAddress"); if ((long)NetworkInterface.LoopbackInterfaceIndex == (long)((ulong)GClass885.smethod_0 <uint>(managementObject, "InterfaceIndex")) & (GClass885.smethod_1(GClass885.smethod_0 <string>(managementObject, "PreferredLifetime"), TimeSpan.FromHours(24.0)) && (hashSet_0 == null || hashSet_0.Contains(item)))) { managementObject.Delete(); } } }
private bool RemoveFilter(string name) { try { ManagementObject filter = new ManagementObject(@"root\subscription:__EventFilter.Name='" + name + "'"); filter.Delete(); Debug.WriteLine("Successfully deleted WMI event filter: " + name); return(true); } catch { Debug.WriteLine("Error occurred deleting filter with name: " + name); } return(false); }
private bool RemoveBinding(string WmiPath) { try { ManagementObject binding = new ManagementObject(WmiPath); binding.Delete(); Debug.WriteLine("Successfully deleted WMI event binding: " + WmiPath); return(true); } catch { Debug.WriteLine("Error occurred deleting WMI event binding: " + WmiPath); } return(false); }
private bool RemoveConsumer(string name, string ConsumerClass) { try { ManagementObject consumer = new ManagementObject(@"root\subscription:" + ConsumerClass + ".Name='" + name + "'"); consumer.Delete(); Debug.WriteLine("Successfully deleted WMI event consumer type (" + ConsumerClass + ") named: " + name); return(true); } catch { Debug.WriteLine("Error occurred deleting consumer type (" + ConsumerClass + ") named: " + name); } return(false); }
private void TryDeletePrintJob(Dictionary <string, string> printJobMap, ManagementObject job) { try { var printJobName = (string)job["Document"]; var jobId = (string)job["Name"]; var commaIndex = jobId.LastIndexOf(','); var printerName = jobId.Substring(0, commaIndex); if (printJobMap.ContainsKey(printJobName) && printerName.Equals(printJobMap[printJobName])) { job.Delete(); } } catch (Exception) {} }
public void Create_Modify_Delete_Static_And_Instance() { using (var newClass = new ManagementClass(WmiTestHelper.Namespace)) { const string NewClassName = "CoreFX_Create_Static_Class_And_Instance"; const string KeyPropertyName = "Key"; const int KeyPropertyValue = 1; const string MoviePropertyName = "Movie"; const string OldMovieValue = "Sequel I"; const string NewMovieValue = "Sequel II"; newClass["__CLASS"] = NewClassName; newClass.Properties.Add(KeyPropertyName, CimType.SInt32, false); newClass.Properties[KeyPropertyName].Qualifiers.Add("key", true); newClass.Properties.Add(MoviePropertyName, CimType.String, false); newClass.Put(); ManagementObject newInstance = newClass.CreateInstance(); newInstance[KeyPropertyName] = KeyPropertyValue; newInstance[MoviePropertyName] = OldMovieValue; newInstance.Put(); var targetInstance = new ManagementObject( WmiTestHelper.Namespace, $"{NewClassName}.{KeyPropertyName}='{KeyPropertyValue}'", null); targetInstance.Get(); Assert.Equal(OldMovieValue, targetInstance[MoviePropertyName].ToString()); newInstance[MoviePropertyName] = NewMovieValue; newInstance.Put(); Assert.Equal(NewMovieValue, newInstance[MoviePropertyName].ToString()); targetInstance.Get(); Assert.Equal(NewMovieValue, targetInstance[MoviePropertyName].ToString()); // If any of the steps below fail it is likely that the new class was not deleted, likely it will have to // be deleted via a tool like wbemtest. newInstance.Delete(); ManagementException managementException = Assert.Throws <ManagementException>(() => targetInstance.Get()); Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode); // If any of the steps below fail it is likely that the new class was not deleted, likely it will have to // be deleted via a tool like wbemtest. newClass.Delete(); managementException = Assert.Throws <ManagementException>(() => newClass.Get()); Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode); } }
public virtual void DeleteAccount(string accountName) { ManagementObject objAccount = wmi.GetObject(String.Format("IIsFtpVirtualDirSetting='{0}'", GetAccountPath(SiteId, accountName))); string origPath = (string)objAccount.Properties["Path"].Value; objAccount.Delete(); // remove permissions RemoveFtpFolderPermissions(origPath, accountName); // delete system user account if (SecurityUtils.UserExists(accountName, ServerSettings, UsersOU)) { SecurityUtils.DeleteUser(accountName, ServerSettings, UsersOU); } }
/// <summary> /// Supports managed resources disposal /// </summary> /// <param name="zoneName"></param> public virtual void DeleteZone(string zoneName) { try { using (ManagementObject objZone = GetZone(zoneName)) { if (objZone != null) { objZone.Delete(); } } } catch (Exception ex) { Log.WriteError(ex); } }