private static void EnsureClassExists(SchemaNaming.InstallLogWrapper context, string classPath, SchemaNaming.ClassMaker classMakerFunction) { try { context.LogMessage(string.Concat(RC.GetString("CLASS_ENSURE"), " ", classPath)); ManagementClass managementClass = new ManagementClass(classPath); managementClass.Get(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode != ManagementStatus.NotFound) { throw managementException; } else { context.LogMessage(string.Concat(RC.GetString("CLASS_ENSURECREATE"), " ", classPath)); ManagementClass managementClass1 = classMakerFunction(); managementClass1.Put(); } } }
public void Shutdown() { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); /* You can't shutdown without security privileges */ mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); /* 0 = Log off the network. * 1 = Shut down the system. * 2 = Perform a full reboot of the system. * 4 = Force any applications to quit instead of prompting the user to close them. * 8 = Shut down the system and, if possible, turn the computer off. */ /* Flag 1 means we want to shut down the system. Use "2" to reboot. */ mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public static void Shutdown(string mode) { if (mode == "WMI") { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // Get Security Privilages mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); //Option Flags mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } else if (mode == "Core") { Process.Start("shutdown", "/s /t 0"); } }
/// <summary> /// Clears the DNS Server cache of resource records. /// </summary> /// <param name="server"></param> public static void ClearCache(Server server) { var cache = new ManagementClass(server.m_scope, new ManagementPath("MicrosoftDNS_Cache"), null); cache.Get(); var coll = cache.GetInstances(); List<Cache> cachelist = new List<Cache>(); foreach (ManagementObject cacheobj in coll) cacheobj.InvokeMethod("ClearCache", null); }
public static void ExitWindows(uint uFlags, uint dwReason) { ManagementBaseObject outParams = null; ManagementClass os = new ManagementClass("Win32_OperatingSystem"); os.Get(); os.Scope.Options.EnablePrivileges = true; // enables required security privilege. ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown"); inParams["Flags"] = uFlags.ToString(); inParams["Reserved"] = "0"; foreach (ManagementObject mo in os.GetInstances()) { outParams = mo.InvokeMethod("Win32Shutdown",inParams, null); } }
/// <summary> /// Shutdown the computer /// </summary> public static void Shutdown() { ManagementClass managementClass = new ManagementClass("Win32_OperatingSystem"); managementClass.Get(); managementClass.Scope.Options.EnablePrivileges = true; ManagementBaseObject methodParameters = managementClass.GetMethodParameters("Win32Shutdown"); methodParameters["Flags"] = "1"; methodParameters["Reserved"] = "0"; foreach (ManagementObject managementObject in managementClass.GetInstances()) { managementObject.InvokeMethod("Win32Shutdown", methodParameters, null); } }
private void MainWindow_Closed(object sender, EventArgs e) { if (MessageBox.Show("You must restart your computer to apply these changes.\nRestart now?", string.Empty, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { ManagementClass os = new ManagementClass("Win32_OperatingSystem"); os.Get(); os.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = os.GetMethodParameters("Win32Shutdown"); mboShutdownParams["Flags"] = "6"; mboShutdownParams["Reserved"] = "0"; ManagementBaseObject obj; foreach (ManagementObject instance in os.GetInstances()) obj = instance.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public void ShutDownComputer(int flag) { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system mboShutdownParams["Flags"] = flag; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public static void Shutdown(ShutdownMode shutdownMode) { var mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; var mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system mboShutdownParams["Flags"] = ((int)shutdownMode).ToString(CultureInfo.InvariantCulture); mboShutdownParams["Reserved"] = "0"; foreach (var manObj in mcWin32.GetInstances().Cast<ManagementObject>()) { manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public override void Execute(object context = null) { ActionsHomeModel pc = context as ActionsHomeModel; //Can only be processed if the machine is online... if (pc.Status == ComputerStates.Online || pc.Status == ComputerStates.LoggedOn) { ManagementScope oMs = ConnectToClient(pc.Name); if (oMs != null) { this.DeleteQueryData(oMs, @"root\ccm\Policy", "SELECT * FROM CCM_SoftwareDistribution"); this.DeleteQueryData(oMs, @"root\ccm\Policy", "SELECT * FROM CCM_Scheduler_ScheduledMessage"); this.DeleteQueryData(oMs, @"root\ccm\Scheduler", "SELECT * FROM CCM_Scheduler_History"); //oMs.Path.NamespacePath = @"ROOT\CCM"; ManagementClass oClass = new ManagementClass(oMs, new ManagementPath("SMS_Client"), null); oClass.Get(); ManagementBaseObject inParams = oClass.GetMethodParameters("ResetPolicy"); inParams["uFlags"] = 1; oClass.InvokeMethod("ResetPolicy", inParams, new InvokeMethodOptions()); ManagementBaseObject newParams = oClass.GetMethodParameters("RequestMachinePolicy"); oClass.InvokeMethod("RequestMachinePolicy", newParams, new InvokeMethodOptions()); App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Completed; }), null); } else { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Error; }), null); } } else { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Pending; }), null); } }
internal static void ShutDownComputer() { FindAndKillProcess("Wow"); ManagementBaseObject outParameters = null; var sysOS = new ManagementClass("Win32_OperatingSystem"); sysOS.Get(); // enables required security privilege. sysOS.Scope.Options.EnablePrivileges = true; // get our in parameters ManagementBaseObject inParameters = sysOS.GetMethodParameters("Win32Shutdown"); // pass the flag of 0 = System Shutdown inParameters["Flags"] = "1"; inParameters["Reserved"] = "0"; foreach (ManagementObject manObj in sysOS.GetInstances()) { outParameters = manObj.InvokeMethod("Win32Shutdown", inParameters, null); } Environment.Exit(0); }
public static void Shutdown() { //http://stackoverflow.com/questions/102567/how-to-shutdown-the-computer-from-c-sharp ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system. Use "2" to reboot. mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
/// <summary> /// Shuts down the computer. /// </summary> /// <returns><c>true</c> if the computer was shut down successfully, or <c>false</c> otherwise.</returns> public static bool ShutDown() { try { ManagementClass os = new ManagementClass("Win32_OperatingSystem"); os.Get(); os.Scope.Options.EnablePrivileges = true; ManagementBaseObject parameters = os.GetMethodParameters("Win32Shutdown"); parameters["Flags"] = "1"; // Shut down parameters["Reserved"] = "0"; foreach (ManagementObject obj in os.GetInstances().Cast<ManagementObject>()) { obj.InvokeMethod("Win32Shutdown", parameters, null /* options */); } return true; } catch { return false; } }
/// <summary> /// creates a DNS zone. /// </summary> /// <param name="server">a Server instance</param> /// <param name="zoneName">String representing the name of the zone.</param> /// <param name="zoneType">Type of zone.</param> /// <param name="dsIntegrated">Indicates whether zone data is stored in the Active Directory or in files. If TRUE, the data is stored in the Active Directory; if FALSE, the data is stored in files.</param> /// <param name="dataFileName">Optional - Name of the data file associated with the zone.</param> /// <param name="ipAddr">Optional - IP address of the master DNS Server for the zone.</param> /// <param name="adminEmail">Optional - Email address of the administrator responsible for the zone.</param> /// <returns>the new Zone created</returns> public static Zone CreateZone(Server server, string zoneName, ZoneTypeCreate zoneType, bool dsIntegrated, string dataFileName, string[] ipAddr, string adminEmail) { if (server == null) throw new ArgumentNullException("server is required"); try { ManagementObject mc = new ManagementClass(server.m_scope, new ManagementPath("MicrosoftDNS_Zone"), null); mc.Get(); ManagementBaseObject parameters = mc.GetMethodParameters("CreateZone"); parameters["ZoneName"] = zoneName; parameters["ZoneType"] = (UInt32)zoneType; parameters["DsIntegrated"] = dsIntegrated; if (!string.IsNullOrEmpty(dataFileName)) parameters["DataFileName"] = dataFileName; //if (!string.IsNullOrEmpty(ipAddr)) parameters["IpAddr"] = ipAddr; if (!string.IsNullOrEmpty(adminEmail)) parameters["AdminEmailName"] = adminEmail; return new Zone(new ManagementObject(server.m_scope, new ManagementPath(mc.InvokeMethod("CreateZone", parameters, null)["RR"].ToString()), null)); } catch (ManagementException me) { throw new WMIException(me); } }
///// <summary> ///// Gets all records ///// </summary> ///// <returns></returns> ////records are under zones, not server //public DNSManagement.RR.ResourceRecord[] GetRecords() //{ // var records = new ManagementClass(m_scope, new ManagementPath("MicrosoftDNS_ResourceRecord"), null); // records.Get(); // var coll = records.GetInstances(); // List<DNSManagement.RR.ResourceRecord> recordlist = new List<DNSManagement.RR.ResourceRecord>(); // foreach (ManagementObject rhobj in coll) // recordlist.Add(new DNSManagement.RR.ResourceRecord(rhobj)); // return recordlist.ToArray(); //} /// <summary> /// Gets Statistics /// </summary> /// <returns></returns> public Statistic[] GetStatistics() { var statistics = new ManagementClass(m_scope, new ManagementPath("MicrosoftDNS_Statistic"), null); statistics.Get(); var coll = statistics.GetInstances(); List<Statistic> statisticlist = new List<Statistic>(); foreach (ManagementObject stobj in coll) statisticlist.Add(new Statistic(stobj)); return statisticlist.ToArray(); }
public static void Restart() { _cw("Asked for reboot"); _cw("Rebooting..."); var mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); Console.WriteLine(!TokenAdjuster.EnablePrivilege("SeShutdownPrivilege", true) ? "Could not enable SeShutdownPrivilege" : "Enabled SeShutdownPrivilege"); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; var mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system mboShutdownParams["Flags"] = "6"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { try { manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } catch (ManagementException mex) { Console.WriteLine(mex.ToString()); Console.ReadKey(); } } }
/*public bool DesinstalarSoftware(string strDesinstalacion) { return SoftwareData.DesinstalarSoft(strDesinstalacion); }*/ /// <summary> /// Realiza la opcion de apagado indicada en el flag. /// </summary> /// <param name="flagAccion">Accion definida en Commom.Libs.CommonConst.ShutdownConst</param> public void RealizarAccionApagado(int flagAccion) { try { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // habilito permisos de seguridad para poder realizar opciones //de apagado en el equipo mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // indico la accion que quiero realizar mediante el Flag, el Flag corresponde //a una constante del paquete Common.Lib.CommonConsts.ShutdownConsts. mboShutdownParams["Flags"] = "" + flagAccion; mboShutdownParams["Reserved"] = "0"; //invoco el metodo con los parametros pasados, para las instancias encontradas. foreach (ManagementObject manObj in mcWin32.GetInstances()) { manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } catch (Exception){ } }
private static ManagementClass SafeGetClass(string classPath) { ManagementClass managementClass = null; try { ManagementClass managementClass1 = new ManagementClass(classPath); managementClass1.Get(); managementClass = managementClass1; } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode != ManagementStatus.NotFound) { throw managementException; } } return managementClass; }
/// <summary> /// Loads the server class /// </summary> private void loadServerClass() { if (m_serverClass != null) return; m_serverClass = new ManagementClass(m_scope, new ManagementPath("MicrosoftDNS_Server"), null); m_serverClass.Get(); var coll = m_serverClass.GetInstances(); foreach (ManagementObject o in coll) { m_serverObject = o; break; } }
private static bool DoesClassExist(string objectPath) { bool flag = false; try { ManagementObject managementClass = new ManagementClass(objectPath); managementClass.Get(); flag = true; } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (ManagementStatus.InvalidNamespace != managementException.ErrorCode && ManagementStatus.InvalidClass != managementException.ErrorCode && ManagementStatus.NotFound != managementException.ErrorCode) { throw managementException; } } return flag; }
private void hg_Tick(object sender, EventArgs e) { if (Time > 0) { Time--; lbComment.Text = "Còn lại " + Time.ToString() + " giây"; } else { hg.Enabled = false; if (comboBoxEx1.Text == "Standby") { Application.SetSuspendState(PowerState.Suspend, true, true); } if (comboBoxEx1.Text == "Hibernate") { Application.SetSuspendState(PowerState.Hibernate, true, true); } if (comboBoxEx1.Text == "Logoff") { ExitWindowsEx(0, 0); } if (comboBoxEx1.Text == "Restart") { ExitWindowsEx(2, 0); } if (comboBoxEx1.Text == "Shutdown") { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } } }
bool ForceReboot() { using (var win32OS = new ManagementClass("Win32_OperatingSystem")) { win32OS.Get(); // You can't shutdown without security privileges win32OS.Scope.Options.EnablePrivileges = true; // http://msdn.microsoft.com/en-us/library/aa394058.aspx var args = win32OS.GetMethodParameters("Win32Shutdown"); args["Flags"] = "6"; // Forced Reboot (2 + 4) args["Reserved"] = "0"; // ignored foreach (ManagementObject instance in win32OS.GetInstances()) { // The return code of the method is in the "returnValue" property of the outParams object var outParams = instance.InvokeMethod("Win32Shutdown", args, null); int result = Convert.ToInt32(outParams["returnValue"]); if (result == 0) { if (log.IsDebugEnabled) log.Debug("Win32Shutdown call for forced reboot succeeded"); return true; } else throw new System.ComponentModel.Win32Exception(result); } } return false; }
/// <summary> /// Retrieves all Zones /// </summary> /// <returns></returns> public Zone[] GetZones() { try { var zones = new ManagementClass(m_scope, new ManagementPath("MicrosoftDNS_Zone"), null); zones.Get(); var coll = zones.GetInstances(); List<Zone> zonelist = new List<Zone>(); foreach (ManagementObject zone in coll) zonelist.Add(new Zone(zone)); return zonelist.ToArray(); } catch (ManagementException me) { throw new WMIException(me); } }
/// <summary> /// Return a list of domains managed by this instance of MS DNS Server /// </summary> /// <returns></returns> public DNSDomain[] GetListOfDomains() { ManagementClass mc = new ManagementClass(_scope, new ManagementPath("MicrosoftDNS_Zone"), null); mc.Get(); ManagementObjectCollection collection = mc.GetInstances(); List<DNSDomain> domains = new List<DNSDomain>(); foreach (ManagementObject p in collection) { domains.Add(new DNSDomain(p["ContainerName"].ToString(), p, this)); } return domains.ToArray(); }
private void btnShutdown_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (MessageBox.ShowBox("MessageID12", BMC_Icon.Warning, BMC_Button.YesNo) == System.Windows.Forms.DialogResult.Yes) { var mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); mcWin32.Scope.Options.EnablePrivileges = true; AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History { AuditModuleName = ModuleName.Shutdown, Audit_Screen_Name = "MainScreen", Audit_Desc = "System Shutdown by User-" + SecurityHelper.CurrentUser.UserName, AuditOperationType = OperationType.ADD }); ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } }
/// <summary> /// Create a new DNS host record /// </summary> /// <param name="zone"></param> /// <param name="bindStyleHostEntry"></param> /// <returns></returns> public void CreateDNSRecord(string zone, string bindStyleHostEntry) { try { ManagementObject mc = new ManagementClass(_scope, new ManagementPath("MicrosoftDNS_ResourceRecord"), null); mc.Get(); ManagementBaseObject parameters = mc.GetMethodParameters("CreateInstanceFromTextRepresentation"); parameters["ContainerName"] = zone; parameters["DnsServerName"] = _server; parameters["TextRepresentation"] = bindStyleHostEntry; ManagementBaseObject createdEntry = mc.InvokeMethod("CreateInstanceFromTextRepresentation", parameters, null); //return createdEntry; (no reason unless you changed your mind and wanted to delete it?!) } catch (ManagementException) //the details on this exception appear useless. { throw new ApplicationException("Unable to create the record " + bindStyleHostEntry + ", please check" + " the format and that it does not already exist."); } }
/// <summary> /// Gets the management class. /// </summary> /// <param name="path">The WMI path.</param> /// <returns>The management class.</returns> private static ManagementClass GetManagementClass(string path) { ManagementScope managementScope = GetManagementScope(); ManagementPath managementPath = new ManagementPath(path); using (ManagementClass managementClass = new ManagementClass(managementScope, managementPath, null)) { managementClass.Get(); return managementClass; } }
/// <summary> /// Create a new zone in MS DNS Server /// </summary> /// <param name="zoneName">The zone to create</param> /// <param name="zoneType">The type of zone to create</param> /// <returns>The domain</returns> public DNSDomain CreateNewZone(string zoneName, NewZoneType zoneType) { try { ManagementObject mc = new ManagementClass(_scope, new ManagementPath("MicrosoftDNS_Zone"), null); mc.Get(); ManagementBaseObject parameters = mc.GetMethodParameters("CreateZone"); /* [in] string ZoneName, [in] uint32 ZoneType, [in] boolean DsIntegrated, (will always be false for us, if you need AD integration you will need to change this. [in, optional] string DataFileName, [in, optional] string IpAddr[], [in, optional] string AdminEmailName, */ parameters["ZoneName"] = zoneName; parameters["ZoneType"] = (UInt32)zoneType; parameters["DsIntegrated"] = 0; //false ManagementBaseObject createdEntry = mc.InvokeMethod("CreateZone", parameters, null); DNSDomain d = new DNSDomain(zoneName, createdEntry, this); return d; } catch (ManagementException) //returns generic error when it already exists, I'm guessing this is a generic answer! { throw new ApplicationException("Unable to create the zone " + zoneName + ", please check " + "the format of the name and that it does not already exist."); } }
/// <summary> /// Executes a method with a given Class and method name. /// </summary> /// <param name="oClass">The Class to be used.</param> /// <param name="method">The method name to be executed.</param> /// <returns>Returns a ManagementBaseObject</returns> public ManagementBaseObject ExecuteMethod(ManagementClass oClass, string method) { if (oClass != null) { oClass.Get(); ManagementBaseObject inParams = oClass.GetMethodParameters(method); return oClass.InvokeMethod(method, inParams, new InvokeMethodOptions()); } else { return null; } }
private static ManagementClass SafeGetClass(string classPath) { ManagementClass class2 = null; try { ManagementClass class3 = new ManagementClass(classPath); class3.Get(); class2 = class3; } catch (ManagementException exception) { if (exception.ErrorCode != ManagementStatus.NotFound) { throw exception; } } return class2; }