使用WMI来控制Windows服务

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

代码如下:

+展开
-C#
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
    }
}
如需转载,请注明本文原创自CSDN TJVictor专栏:http://blog.csdn.net/tjvictor

加支付宝好友偷能量挖...


评论(0)网络
阅读(130)喜欢(0)Asp.Net/C#/WCF