• 使用WMI控制Windows进程 和服务


    1.使用WMI控制Windows进程

    本文主要介绍两种WMI的进行操作:检查进程是否存在、创建新进行

    代码如下:

    using System; 
    using System.Collections.Generic; 
    using System.Text; 
    using System.Management; 
    using System.Threading; 
    
    namespace TJVictor.WMI 
    { 
        public class Win32_Process:WMIBaseClass 
        { 
            #region Property 
            private int timeout = 30; 
            public int TimeOut 
            { 
                get { return timeout; } 
                set { timeout = value; } 
            } 
    
            private string wqlSelect = "select * FROM Win32_Process where Name='{0}'"; 
            #endregion 
    
            #region Construction 
            public Win32_Process() 
                : base() 
            { 
                base.Connection(); 
            } 
    
            public Win32_Process(string domain, string Ip, string user, string psd) 
                : base(domain, Ip, user, psd) 
            { 
                base.Connection(); 
            } 
            #endregion 
    
            #region public function 
            public bool IsProcessExist(string name) 
            { 
                if (!GetSelectQueryCollection(wqlSelect,name).Count.Equals(0)) 
                    return true; 
                return false; 
            } 
    
            public void CreateProcess(string name) 
            { 
                ManagementClass processClass = new ManagementClass("Win32_Process"); 
                processClass.Scope = base.Scope; 
    
                ManagementBaseObject mbo = processClass.GetMethodParameters("Create"); 
                mbo["CommandLine"] = string.Format(name); 
                ManagementBaseObject result = processClass.InvokeMethod("Create", mbo, null); 
                //检测执行结果 
                CheckExceptionClass.CheckProcessException(int.Parse(result["returnValue"].ToString())); 
                //检测进程是否执行完成 
                int tempTimeout = this.timeout; 
                while (!GetSelectQueryCollection("select * FROM Win32_Process where ProcessID='{0}'",result["ProcessID"].ToString()).Count.Equals(0)) 
                { 
                    if (tempTimeout.Equals(0)) 
                    { 
                        throw new TJVictor.WMI.WmiException.ProcessException( 
                            string.Format("在 {0} 上执行 {1} 操作失败,执行超时", base.Ip, name)); 
                    } 
                    tempTimeout--; 
                    Thread.Sleep(1000); 
                } 
            } 
            #endregion 
        } 
    }

    2.使用WMI来控制Windows服务

    本文介绍如何使用WMI来判断服务是否存在、如何创建新服务,删除服务、如何启服务、停服务

    代码如下:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Management;
    using System.Threading;
    
    namespace TJVictor.WMI
    {
        public class Win32_Service:WMIBaseClass
        {
            #region Property
            private bool completed = false;
            private int timeout = 30;
            public int TimeOut
            {
                get { return timeout; }
                set { timeout = value; }
            }
    
            private string wqlSelect = string.Empty;
            #endregion
    
            #region Construction
            public Win32_Service()
                : base()
            {
                wqlSelect = "select * FROM Win32_Service where Name='{0}'";
                base.Connection();
            }
    
            public Win32_Service(string domain, string Ip, string user, string psd)
                : base(domain, Ip, user, psd)
            {
                wqlSelect = "select * FROM Win32_Service where Name='{0}'";
                base.Connection();
            }
            #endregion
    
            #region public function
            public bool IsServiceExist(string name)
            {
                
                if (!GetSelectQueryCollection(wqlSelect,name).Count.Equals(0))
                    return true;
                return false;
            }
    
            public void StartService(string name)
            {
                if(!IsServiceExist(name))
                    throw new TJVictor.WMI.WmiException.ServiceException(string.Format("{0} 服务不存在",name));
                object result = string.Empty;
                ManagementObjectSearcher mos = GetObjectSearcher(wqlSelect, name);
                foreach (ManagementObject mo in mos.Get())
                {
                    result = mo.InvokeMethod("StartService", null);
                    break;
                }
                CheckExceptionClass.CheckServiceException(int.Parse(result.ToString()));
                TestServiceState(mos, "Running", string.Format("{0} 服务在 {1} 机器上启动失败,启动超时",name,base.Ip));
            }
    
            public void StopService(string name)
            {
                if (!IsServiceExist(name))
                    throw new TJVictor.WMI.WmiException.ServiceException(string.Format("{0} 服务不存在", name));
                object result = string.Empty;
                ManagementObjectSearcher mos = GetObjectSearcher(wqlSelect, name);
                foreach (ManagementObject mo in mos.Get())
                {
                    result = mo.InvokeMethod("StopService", null);
                    break;
                }
                CheckExceptionClass.CheckServiceException(int.Parse(result.ToString()));
                TestServiceState(mos, "Stopped", string.Format("{0} 服务在 {1} 机器上停止失败,停止超时", name, base.Ip));
            }
    
            public void CreateService(string name, string displayName, string startMode, string pathName, string startName, string startPassword,
                string serviceType)
            {
                if(IsServiceExist(name))
                    throw new TJVictor.WMI.WmiException.ServiceException(string.Format("{0} 服务已经存在",name));
    
                int tempTimeout = this.timeout;
                ManagementClass processClass = new ManagementClass("Win32_Service");
                processClass.Scope = base.Scope;
    
                string method = "Create";
                ManagementBaseObject inputArgs = processClass.GetMethodParameters(method);
                inputArgs["Name"] = name;
                inputArgs["DisplayName"] = displayName;
                inputArgs["StartMode"] = startMode;
                inputArgs["PathName"] = pathName;
                if (!startName.Equals(string.Empty))
                {
                    inputArgs["StartName"] = startName;
                    inputArgs["StartPassword"] = startPassword;
                }
                ManagementBaseObject ob = processClass.InvokeMethod(method, inputArgs, null);
                CheckExceptionClass.CheckServiceException(int.Parse(ob["returnValue"].ToString()));
    
                //检测服务是否已经安装成功
                while (!IsServiceExist(name))
                {
                    if (tempTimeout.Equals(0))
                    {
                        throw new TJVictor.WMI.WmiException.ServiceException(
                            string.Format("在 {0} 上安装 {1} 服务超时", base.Ip, name));
                    }
                    Thread.Sleep(1000);
                    tempTimeout--;
                } 
            }
    
            public void DeleteService(string name)
            {
                object result = string.Empty;
                if(!IsServiceExist(name))
                    throw new TJVictor.WMI.WmiException.ServiceException(string.Format("{0} 服务不存在",name));
                foreach (ManagementObject mo in GetSelectQueryCollection(wqlSelect, name))
                {
                    result = mo.InvokeMethod("delete", null);
                    break;
                }
                //检测卸载命令是否执行成功
                CheckExceptionClass.CheckServiceException(int.Parse(result.ToString()));
                //检测服务是否已经卸载成功
                int tempTimeout = this.timeout;
                while (IsServiceExist(name))
                {
                    if (tempTimeout.Equals(0))
                    {
                        throw new TJVictor.WMI.WmiException.ServiceException(
                            string.Format("在 {0} 上卸载 {1} 服务超时", base.Ip, name));
                    }
                    Thread.Sleep(1000);
                    tempTimeout--;
                }
            }
            #endregion
    
            #region private function
            private void TestServiceState(ManagementObjectSearcher mos, string state,string errorMes)
            {
                completed = false;
                int tempTimeout = timeout;
                while (!completed)
                {
                    if (tempTimeout.Equals(0))
                    {
                        throw new TJVictor.WMI.WmiException.ServiceException(errorMes);
                    }
                    foreach (ManagementObject mo in mos.Get())
                    {
                        if (mo["State"].ToString().Equals(state))
                        {
                            completed = true;
                        }
                        break;
                    }
                    Thread.Sleep(1000);
                    tempTimeout--;
                }
            }
            #endregion
        }
    }
  • 相关阅读:
    关于OC中.m文件下实现私有变量的方法,在.h文件下实现公有变量的方法
    mac中安装homebrew
    ios架构
    github命令记录
    Unity 游戏框架搭建 MonoBehaviour单例的模板
    Unity 游戏框架搭建 单例的模板
    unity 单列
    简单工厂与工厂
    NGUI动态播放视频
    在一个GameObject上进行多个AudioSource的控制
  • 原文地址:https://www.cnblogs.com/tianma3798/p/3560608.html
Copyright © 2020-2023  润新知