Beispiel #1
0
        public void Create_Modify_Delete_Static_Class()
        {
            using (var newClass = new ManagementClass(WmiTestHelper.Namespace))
            {
                const string NewClassName  = "CoreFX_Create_Modify_Delete_Static_Class\uEE68\uD79D\u1659";
                const string PropertyName  = "Key";
                const int    PropertyValue = 10;

                newClass["__CLASS"] = NewClassName;
                newClass.Properties.Add(PropertyName, CimType.SInt32, false);
                newClass.Properties[PropertyName].Qualifiers.Add("key", true);
                newClass.Put();

                var targetClass = new ManagementClass(WmiTestHelper.Namespace, NewClassName, null);
                targetClass.Get();

                newClass[PropertyName] = PropertyValue;
                newClass.Put();
                targetClass.Get();
                Assert.Equal(PropertyValue, (int)targetClass[PropertyName]);

                // 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 managementException = Assert.Throws <ManagementException>(() => targetClass.Get());
                Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Execute a WMI Method
        /// </summary>
        /// <param name="WMIPath"></param>
        /// <param name="Method"></param>
        /// <param name="inParams"></param>
        /// <returns></returns>
        public ManagementBaseObject ExecuteMethod(string WMIPath, string Method, ManagementBaseObject inParams)
        {
            ManagementClass SMSClass = GetClass(WMIPath);

            SMSClass.Get();
            return(SMSClass.InvokeMethod(Method, inParams, new InvokeMethodOptions()));
        }
Beispiel #3
0
        /// <summary>
        ///  Shutdown,restart and log off Computer
        /// </summary>
        /// <param name="Flags">Specify the Shut down Parameter
        ///  "1" - Shut down
        ///  "2" - Restart
        ///  "0" - Log off
        /// </param>
        public static void ShutDownWindows(String Flags)
        {
            try
            {
                ManagementBaseObject MBOShutdown = null;
                ManagementClass      MCWin32     = new ManagementClass("Win32_OperatingSystem");
                MCWin32.Get();


                MCWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject MBOShutdownParams = MCWin32.GetMethodParameters("Win32Shutdown");

                MBOShutdownParams["Flags"]    = Flags;
                MBOShutdownParams["Reserved"] = "0";

                foreach (ManagementObject manObj in MCWin32.GetInstances())
                {
                    MBOShutdown = manObj.InvokeMethod("Win32Shutdown", MBOShutdownParams, null);
                }
            }
            catch (Exception ex)
            {
                Locker.AppLogger.Error("ShutDownWindows()", "RunMode is " + Flags + ". Exception: " + ex.Message);
            }
        }
Beispiel #4
0
 public SystemManagmentOperator()
 {
     _mcWin32 = new ManagementClass("Win32_OperatingSystem");
     _mcWin32.Get();
     _mcWin32.Scope.Options.EnablePrivileges = true;
     _mboShutdownParams = _mcWin32.GetMethodParameters("Win32Shutdown");
 }
Beispiel #5
0
        public static void OperatingWin32(int mode)
        {
            ManagementBaseObject mboShutdown = null;

            using (ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"))
            {
                mcWin32.Get();
                // без прав ничего не выйдет
                mcWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject mboShutdownParams =
                    mcWin32.GetMethodParameters("Win32Shutdown");
                // 0 - завершение сеанса
                // 1 - завершение работы системы
                // 2 - перезагрузка
                // 4 - принудительное завершение сеанса
                // 5 - принудительное завершение работы системы
                // 6 - принудительная перезагрузка
                // 8 - выключение питания
                // 12 - принудительное выключение питания
                mboShutdownParams["Flags"]    = mode.ToString();
                mboShutdownParams["Reserved"] = "0";
                foreach (ManagementObject manObj in mcWin32.GetInstances())
                {
                    mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
                }
            }
        }
Beispiel #6
0
        public static void ShutdownWMI(ShutdownAction action)
        {
            if (action == ShutdownAction.None)
            {
                return;
            }
            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.
            switch (action)
            {
            case ShutdownAction.Logoff: mboShutdownParams["Flags"] = "0"; break;

            case ShutdownAction.Reboot: mboShutdownParams["Flags"] = "2"; break;

            case ShutdownAction.Shutdown: mboShutdownParams["Flags"] = "1"; break;

            default: mboShutdownParams["Flags"] = "0"; break;
            }

            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                                  mboShutdownParams, null);
            }
        }
Beispiel #7
0
        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();
                }
            }
        }
Beispiel #8
0
        public void Shutdown()
        {
            ManagementBaseObject mboShutdown = null;
            ManagementClass      mcWin32     = new ManagementClass("Win32_OperatingSystem");

            mcWin32.Get();
            if (!TokenAdjuster.EnablePrivilege("SeShutdownPrivilege", true))
            {
                Console.WriteLine("Could not enable SeShutdownPrivilege");
            }
            else
            {
                Console.WriteLine("Enabled SeShutdownPrivilege");
            }
            // 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"]    = "1";
            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                try
                {
                    mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                                      mboShutdownParams, null);
                }
                catch (ManagementException mex)
                {
                    Console.WriteLine(mex.ToString());
                    Console.ReadKey();
                }
            }
        }
Beispiel #9
0
        public void shutdown()
        {
            /*
             * uint32 Win32Shutdown(
             * [in] sint32 Flags,
             * [in] sint32 Reserved =
             * );
             *
             * WMIServiceObject = GetObject(
             * "Winmgmts:{impersonationLevel=impersonate,(Debug,Shutdown)}")
             * ForEach ComputerObject In WMIServiceObject.InstancesOf("Win32_OperatingSystem")
             * testResult = ComputerObject.Win32Shutdown(2 + 4, 0)
             * 'reboot
             * 'testResult = ComputerObject.Win32Shutdown(0, 0) 'logoff
             * ' testResult = ComputerObject.Win32Shutdown(8 + 4, 0) 'shutdown
             *
             */

            ManagementClass mClass = new ManagementClass("Win32_OperatingSystem");

            mClass.Get();
            ManagementBaseObject mboClass_shutdown = mClass.GetMethodParameters("Win32Shutdown");

            //label5.Text = mboClass_shutdown.GetType().ToString();
            mClass.Scope.Options.EnablePrivileges = true;
            mboClass_shutdown["Flags"]            = 1;
            mboClass_shutdown["Reserved"]         = 0;
            foreach (ManagementObject moClass in mClass.GetInstances())
            {
                //moClass.InvokeMethod("Win32Shutdown", mboClass_shutdown, null);
            }
        }
        ///// <summary>
        ///// 待机
        ///// </summary>
        ///// <param name="hiberate"></param>
        ///// <param name="forceCritical"></param>
        ///// <param name="disableWakeEvent"></param>
        ///// <returns></returns>
        //[DllImport("Powrprof.dll",CharSet = CharSet.Auto,ExactSpelling = true)]
        //public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent);

        /// <summary>
        /// 退出windows, 关闭计算机
        /// </summary>
        /// <param name="flag">
        /// 关闭系统的参数。
        ///0 Log off用户退出
        ///4 Forced Log off 强制用户退出
        ///1 Shutdown 关闭操作系统
        ///5 Forced Shutdown 强制关闭操作系统
        ///2 Reboot 重启
        ///6 Forced Reboot 强制重启
        ///8 Power Off - Shuts down the computer and turns off the power (if supported by the computer in question).
        ///12 Forced Power Off
        /// </param>
        /// <param name="reversed"> A means to extend Win32Shutdown. Currently, the Reserved parameter is ignored.</param>
        private static void ExitWin(int flag, int reversed)
        {
            ManagementBaseObject mboShutDown = null;
            //初始化一个公共信息模型的管理类,初始化到当前机器上的所有windows的系统
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");

            mcWin32.Get();//绑定到管理对象
            //启用用户特权,否则不能关闭
            mcWin32.Scope.Options.EnablePrivileges = true;

            //获取Win32Shutdown方法的参数,该方法提供了提供了操作系统支持的所有关闭系统的参数
            ManagementBaseObject mboShutDownParams = mcWin32.GetMethodParameters("Win32Shutdown");

            //设置参数的值
            //关闭系统的参数。
            //0 Log off用户退出
            //4 Forced Log off 强制用户退出
            //1 Shutdown 关闭操作系统
            //5 Forced Shutdown 强制关闭操作系统
            //2 Reboot 重启
            //6 Forced Reboot 强制重启
            //8 Power Off - Shuts down the computer and turns off the power (if supported by the computer in question).
            //12 Forced Power Off
            mboShutDownParams["Flags"] = flag;
            //Reserved :  A means to extend Win32Shutdown. Currently, the Reserved parameter is ignored.
            mboShutDownParams["Reserved"] = reversed;

            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutDown = manObj.InvokeMethod("Win32Shutdown", mboShutDownParams, null);
            }
        }
Beispiel #11
0
        private bool CreatePrinter()
        {
            try
            {
                var printerClass = new ManagementClass(managementScope, new ManagementPath("Win32_Printer"), new ObjectGetOptions());
                printerClass.Get();
                var printer = printerClass.CreateInstance();
                printer.SetPropertyValue("DriverName", appsettings.DriverName);
                printer.SetPropertyValue("PortName", appsettings.PrinterIP);
                //printer.SetPropertyValue("DisplayName", appsettings.PrinterName);
                printer.SetPropertyValue("Name", appsettings.PrinterName);
                printer.SetPropertyValue("DeviceID", appsettings.PrinterName);
                printer.SetPropertyValue("Location", "Office");
                printer.SetPropertyValue("Network", true);
                printer.SetPropertyValue("Shared", false);
                printer.Put();
                printer.InvokeMethod("SetDefaultPrinter", null);
                printer.InvokeMethod("PrintTestPage", null);

                ok = true;
                return(true);
            }
            catch (ManagementException ex)
            {
                return(false);
            }
        }
Beispiel #12
0
        private bool CreatePrinterPort()
        {
            try
            {
                if (CheckPrinterPort())
                {
                    MessageBox.Show("Port already exists!");
                    return(true);
                }
                var printerPortClass = new ManagementClass(managementScope, new ManagementPath("Win32_TCPIPPrinterPort"), new ObjectGetOptions());
                printerPortClass.Get();
                var newPrinterPort = printerPortClass.CreateInstance();
                newPrinterPort.SetPropertyValue("Name", textBoxhostaddress.Text);
                if (radioraw.Checked)
                {
                    newPrinterPort.SetPropertyValue("Protocol", 1);
                }
                else if (radiolpr.Checked)
                {
                    newPrinterPort.SetPropertyValue("Protocol", 2);
                }
                newPrinterPort.SetPropertyValue("HostAddress", textBoxhostaddress.Text);
                newPrinterPort.SetPropertyValue("PortNumber", textBoxportno.Text); // default=9100
                newPrinterPort.SetPropertyValue("SNMPEnabled", false);             // true?
                newPrinterPort.SetPropertyValue("Queue", textBoxqname.Text);

                newPrinterPort.Put();
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Create Printer Port FAILED");
                return(false);
            }
        }
        private static void RunWin32Shutdown(Win32ShutdownFlag shutdownFlags)
        {
            // 参考:
            // WMIを利用してWindowsをログオフ、シャットダウン、再起動する[C#] | JOHOBASE
            // https://johobase.com/wmi-os-shutdown-csharp/

            var thread = new Thread(() =>
            {
                // Win32_OperatingSystemクラスを作成する
                using (var managementClass = new ManagementClass("Win32_OperatingSystem")) {
                    // Win32_OperatingSystemオブジェクトを取得する
                    managementClass.Get();
                    // 権限を有効化する
                    managementClass.Scope.Options.EnablePrivileges = true;

                    var managementObjectCollection = managementClass.GetInstances();
                    foreach (ManagementObject managementObject in managementObjectCollection)
                    {
                        managementObject.InvokeMethod("Win32Shutdown", new object[] { shutdownFlags, 0 });
                        managementObject.Dispose();
                    }
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
        }
Beispiel #14
0
        public static int Main(string[] args)
        {
            ManagementClass MgmtsubclassObj = new ManagementClass();

            MgmtsubclassObj.Scope   = new ManagementScope("root\\cimv2");
            MgmtsubclassObj.Path    = new ManagementPath("Win32_Processor");
            MgmtsubclassObj.Options = new ObjectGetOptions();
            MgmtsubclassObj.Get();
            foreach (Qualifier Qual in MgmtsubclassObj.Qualifiers)
            {
                Console.WriteLine("Qualifier    : {0} = {1}", Qual.Name, Qual.Value);
            }
            Console.ReadLine();
            foreach (Property Prop in MgmtsubclassObj.Properties)
            {
                if (null == Prop.Value)
                {
                    Console.WriteLine("Property   : {0}", Prop.Name);
                }
                else
                {
                    Console.WriteLine("Property   : {0} = {1}", Prop.Name, Prop.Value);
                }
            }
            Console.ReadLine();
            return(0);
        }
Beispiel #15
0
 private static void OperatingWin32(int mode)
 {
     using (var mcWin32 = new ManagementClass("Win32_OperatingSystem"))
     {
         mcWin32.Get();
         // без прав ничего не выйдет
         mcWin32.Scope.Options.EnablePrivileges = true;
         var mboShutdownParams =
             mcWin32.GetMethodParameters("Win32Shutdown");
         // 0 - завершение сеанса
         // 1 - завершение работы системы
         // 2 - перезагрузка
         // 4 - принудительное завершение сеанса
         // 5 - принудительное завершение работы системы
         // 6 - принудительная перезагрузка
         // 8 - выключение питания
         // 12 - принудительное выключение питания
         mboShutdownParams["Flags"]    = mode.ToString(CultureInfo.InvariantCulture);
         mboShutdownParams["Reserved"] = "0";
         foreach (var manObj in mcWin32.GetInstances().Cast <ManagementObject>().
                  Where(manObj => manObj != null))
         {
             manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
         }
     }
 }
Beispiel #16
0
        public static int Main(string[] args)
        {
            string mylocale = "ms_409";

            try
            {
                // Setting the ManagementObject with the ConnectionOptions
                ConnectionOptions con = new ConnectionOptions(
                    mylocale,
                    ".\\Administrator",
                    "",
                    null,
                    ImpersonationLevel.Impersonate,
                    AuthenticationLevel.None,
                    false,
                    null);

                ManagementPath  mypath  = new ManagementPath("Win32_LogicalDisk");
                ManagementScope myscope = new ManagementScope("\\\\w23-wmichssp17\\root\\cimv2", con);
                ManagementClass pobj    = new ManagementClass(myscope, mypath, null);
                pobj.Get();
                Console.WriteLine(pobj.Scope.Options.Authentication);
                Console.WriteLine(pobj["__PATH"]);
            }
            catch (ManagementException e)
            {
                Console.WriteLine("Access is Denied and cannot open class. " + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + e.StackTrace);
            }
            return(0);
        }
        public void Shutdown(bool restart)
        {
            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.
            if (restart)
            {
                mboShutdownParams["Flags"] = "2";
            }
            else
            {
                mboShutdownParams["Flags"] = "1";
            }
            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                                  mboShutdownParams, null);
            }
        }
Beispiel #18
0
        /// <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.");
            }
        }
Beispiel #19
0
        public static void Shutdown(ShutdownType type)
        {
            switch (type)
            {
            case ShutdownType.Lock:
                LockWorkStation();
                break;

            case ShutdownType.Standby:
                Application.SetSuspendState(PowerState.Suspend, true, true);
                break;

            case ShutdownType.Hibernate:
                Application.SetSuspendState(PowerState.Hibernate, true, true);
                break;

            default:
                ManagementBaseObject mbo     = null;
                ManagementClass      mcWin32 = new ManagementClass("Win32_OperatingSystem");
                mcWin32.Get();

                mcWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject mboParams =
                    mcWin32.GetMethodParameters("Win32Shutdown");

                mboParams["Flags"]    = ((int)type).ToString();
                mboParams["Reserved"] = "0";
                foreach (ManagementObject manObj in mcWin32.GetInstances())
                {
                    mbo = manObj.InvokeMethod("Win32Shutdown",
                                              mboParams, null);
                }
                break;
            }
        }
Beispiel #20
0
        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);
            }
        }
        /// <summary>
        /// シャットダウン等の処理
        /// 参考(というか必要としてるそのものなのでほぼ丸コピ): https://johobase.com/wmi-os-shutdown-csharp/
        /// </summary>
        /// <param name="shutdownFlags">シャットダウン動作の種類 内容は以下のWin32ShutdownFlagsの定義参照</param>
        private static void Win32Shutdown(int shutdownFlags)
        {
            Thread thread = new Thread(() =>
            {
                // Win32_OperatingSystemクラスの作成
                using (ManagementClass managementClass = new ManagementClass("Win32_OperatingSystem"))
                {
                    // Win32_OperatingSystemオブジェクトの取得
                    managementClass.Get();
                    // 権限有効化
                    managementClass.Scope.Options.EnablePrivileges = true;
                    // コレクション取得
                    ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();

                    // WMIオブジェクト列挙
                    foreach (ManagementObject managementObject in managementObjectCollection)
                    {
                        // InvokeMethodでWMIメソッド実行
                        managementObject.InvokeMethod(
                            "Win32Shutdown",
                            new object[] { shutdownFlags, 0 }
                            );
                        // リソース開放
                        managementObject.Dispose();
                    }
                }
            });

            // スレッドモデルをSTAに
            thread.SetApartmentState(ApartmentState.STA);
            // スレッド実行
            thread.Start();
            // スレッド終了待ち
            thread.Join();
        }
Beispiel #22
0
        private void PowerOff()
        {
            ManagementBaseObject outParameters = null;
            ManagementClass      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
            if (ForceQuitCheckBox.Checked)
            {
                inParameters["Flags"] = "12";
            }
            else
            {
                inParameters["Flags"] = "8";
            }
            inParameters["Reserved"] = "0";
            foreach (ManagementObject manObj in sysOS.GetInstances())
            {
                outParameters = manObj.InvokeMethod("Win32Shutdown", inParameters, null);
            }
        }
Beispiel #23
0
        private void PowerControl(string flag)
        {
#pragma warning disable IDE0067 // 丢失范围之前释放对象
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
#pragma warning restore IDE0067 // 丢失范围之前释放对象
            try
            {
                mcWin32.Get();

                mcWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

                //"0" 注销 "1" 关机, "2" 重启 "8" 关闭计算机电源
                mboShutdownParams["Flags"]    = flag;
                mboShutdownParams["Reserved"] = "0";
                foreach (ManagementObject manObj in mcWin32.GetInstances())
                {
                    ManagementBaseObject mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mcWin32.Dispose();
            }
        }
Beispiel #24
0
 protected void initWMI()
 {
     if (mcWin32 == null)
     {
         mcWin32 = new ManagementClass("Win32_OperatingSystem");
     }
     mcWin32.Get();
 }
Beispiel #25
0
        public void ProcessData()
        {
            obj = new ManagementClass("Win32_Environment");
            obj.Get();

            //
            // Use data member reference
            //
        }
Beispiel #26
0
        /// <summary>
        /// Execute a WMI Method
        /// </summary>
        /// <param name="WMIPath"></param>
        /// <param name="Method"></param>
        /// <returns></returns>
        public ManagementBaseObject ExecuteMethod(string WMIPath, string Method)
        {
            //ManagementPath Path = new ManagementPath(WMIPath);
            ManagementClass WMIClass = GetClass(WMIPath);

            WMIClass.Get();
            ManagementBaseObject Params = WMIClass.GetMethodParameters(Method);

            return(WMIClass.InvokeMethod(Method, Params, new InvokeMethodOptions()));
        }
Beispiel #27
0
 public RestartAction( )
 {
     outParameters = null;
     sysOS         = new ManagementClass("Win32_OperatingSystem");
     sysOS.Get();
     // enables required security privilege.
     sysOS.Scope.Options.EnablePrivileges = true;
     // get our in parameters
     inParameters = sysOS.GetMethodParameters("Win32Shutdown");
 }
        /// <summary>
        /// Gets a management class for working with BizTalk management objects
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ManagementClass GetManagementClass(string path)
        {
            var managementScope = GetManagementScope();
            var managementPath  = new ManagementPath(path);
            var managementClass = new ManagementClass(managementScope, managementPath, null);

            managementClass.Get();

            return(managementClass);
        }
 public ClassAnalyzerForm(string className)
 {
     InitializeComponent();
     this.className = className;
     this.Text      = this.className;
     mgmtClass      = new ManagementClass(this.className);
     mgmtClass.Get();
     AddInstances();
     AddProperties(mgmtClass);
     AddMethods();
 }
Beispiel #30
0
        private void Restart()
        {
            if (akcia <= 2)
            {
                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"]    = akcia;
                mboShutdownParams["Reserved"] = "0";
                foreach (ManagementObject manObj in mcWin32.GetInstances())
                {
                    mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                                      mboShutdownParams, null);
                }
            }
            else if (akcia == 3)
            {
                akcia = 0;
                bool retVal = Application.SetSuspendState(PowerState.Hibernate, false, false);

                if (retVal == false)
                {
                    MessageBox.Show("Could not hybernate the system.");
                }
            }
            else if (akcia == 4)
            {
                akcia = 0;
                bool retVal = Application.SetSuspendState(PowerState.Suspend, false, false);

                if (retVal == false)
                {
                    MessageBox.Show("Could not suspend the system.");
                }
            }
            else if (akcia == 5)
            {
                akcia = 0;
                bool result = LockWorkStation();

                if (result == false)
                {
                    // An error occured
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
        }