使用WMI来控制Windows服务

本文介绍了一种利用Windows Management Instrumentation (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
    }
}

<!-- .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } -->

如需转载,请注明本文原创自优快云 TJVictor专栏:http://blog.youkuaiyun.com/tjvictor

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值