使用WMI控制Windows进程 和服务

摘要:
GetSelectQueryCollection.Count.Equals){if{thrownewTJVictor.WMI.WmiException.ProcessException;}tempTimeout--;线睡眠;}}#Endregion}2.使用WMI控制Windows服务。本文描述了如何使用WMI来确定服务是否存在、创建新服务、删除服务、启动服务和停止服务。代码如下:usingSystem;使用System.Collections。通用的使用系统。文本使用系统。经营使用系统。穿线;namespaceTJVictor。WMI{publicclassWin32_Service:WMIBaseClass{#regionPropertyprivateboolcompleted=false;privateinttimeout=30;publicintTimeOut{get{returntimeout;}设置{timeout=value;}}privatestringqlSelect=string。空;#endregion#regionConstructionpublicWin32_Service():base(){wqlSelect=“select*FROMWin32_ServicewhereName=‘{0}’”;基础连接();}publicWin32_Service:base{wqlSelect=“select*FROMWin32_ServicewhereName=‘{0}’”;基础Connection();}#endregion#regionpublicfunctionpublicboolIsServiceExist{if(!

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
    }
}

免责声明:文章转载自《使用WMI控制Windows进程 和服务》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇UNIX网络编程——带外数据EcShop二次开发系列教程–用户注册下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

【java开发系列】—— java输入输出流

前言   任何语言输入输出流都是很重要的部分,比如从一个文件读入内容,进行分析,或者输出到另一个文件等等,都需要文件流的操作。这里简单介绍下reader,wirter,inputstream,outputstream的使用方法。其实Apache commons里面有个方法IOUtils可是实现方便快捷的流拷贝,感兴趣的可以参考官方文档。   JAVA的...

[开源项目]Hibernate基本使用

开源项目(1)Hibernate基本使用 Hibernate介绍 Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。  官网  http://hibernate.org/  以下为其原理和基本的结构示意图 一步一步简单讲述其基本应用 1、创建java...

C#--反射基础

以下是学习笔记: 一,反射的基本信息 DLL/EXE: 主要区别EXE文件有一个入口,DLL文件不能运行,但是DLL能拿到其他地方去使用 metadata(元数据):描述exe/dll文件的一个清单,记录了exe/dll文件中有哪些类,属性,特性,字段。。。 Reflection(反射):用来操作或获取元数据metadata 有什么作用: 1,更新程序(...

RabbitMQ学习07--消息重复消费

幂等性操作 :可以重复执行的操作,可以不用保证消息重复消费。 非幂等性,需要保证消息不会被重复消费。 重复消费原因:消费者消费了消息,但并没有向rabbitmq发送ack。 为了解决消费重复消费的问题,可以使用Redis,在消费者消费之前,先将消息的id放到Redis中, id-0(正在执行业务) id-1(业务执行成功) 如果ack失败,在RabbitM...

消息中间件系列三:使用RabbitMq原生Java客户端进行消息通信(消费者(接收方)自动确认模式、消费者(接收方)自行确认模式、生产者(发送方)确认模式)

准备工作: 1)安装RabbitMQ,参考文章:消息中间件系列二:RabbitMQ入门(基本概念、RabbitMQ的安装和运行) 2.)分别新建名为OriginalRabbitMQProducer和OriginalRabbitMQConsumer的maven工程 在pom.xml文件里面引入如下依赖: <dependency>...

Directory.GetFiles()获取多个类型格式的文件

第一种(用通配符) 1   string[] fileNameX = Directory.GetFiles(@"D:Sjdc", "*.xls?"); 2   Array array = Array.CreateInstance(typeof(string),fileNameX.Length); 3   fileNameX.CopyTo(array, 0)...