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 = ;
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())
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())
{
if (tempTimeout.Equals())
{
throw new TJVictor.WMI.WmiException.ProcessException(
string.Format("在 {0} 上执行 {1} 操作失败,执行超时", base.Ip, name));
}
tempTimeout--;
Thread.Sleep();
}
}
#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 = ;
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())
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())
{
throw new TJVictor.WMI.WmiException.ServiceException(
string.Format("在 {0} 上安装 {1} 服务超时", base.Ip, name));
}
Thread.Sleep();
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())
{
throw new TJVictor.WMI.WmiException.ServiceException(
string.Format("在 {0} 上卸载 {1} 服务超时", base.Ip, name));
}
Thread.Sleep();
tempTimeout--;
}
}
#endregion #region private function
private void TestServiceState(ManagementObjectSearcher mos, string state,string errorMes)
{
completed = false;
int tempTimeout = timeout;
while (!completed)
{
if (tempTimeout.Equals())
{
throw new TJVictor.WMI.WmiException.ServiceException(errorMes);
}
foreach (ManagementObject mo in mos.Get())
{
if (mo["State"].ToString().Equals(state))
{
completed = true;
}
break;
}
Thread.Sleep();
tempTimeout--;
}
}
#endregion
}
}

使用WMI控制Windows进程 和服务的更多相关文章

  1. 使用WMI来控制Windows目录 和windows共享机制

    1.使用WMI来控制Windows目录 本文主要介绍如何使用WMI来查询目录是否存在.文件是否存在.如何建立目录.删除目录,删除文件.如何利用命令行拷贝文件,如何利用WMI拷贝文件 using Sys ...

  2. C# ASP.NET 控制windows服务的 开启和关闭 以及重启

    用ASP.NET控制Windows服务的开启与关闭效果如图 代码 首页页面需要添加引用 页面的pageload中 实例化windows服务 protected void Page_Load(objec ...

  3. Windows根据端口号查找对应的进程和服务

    需求 1,我们在Win10安装一些Web服务时,会发现默认端口被占用,比如443端口被占用,808端口被占用,那么如何找出占用这些默认端口的进程和对应的服务呢? 2,系统安装完成后,会有一些应用对外开 ...

  4. windows进程详解

    1:系统必要进程system process    进程文件: [system process] or [system process]进程名称: Windows内存处理系统进程描述: Windows ...

  5. Inno Setup 安装、卸载前检测进程或服务

    [转载]Inno Setup 安装.卸载前检测进程或服务 (2015-04-24 17:37:20) 转载▼ 标签: 转载   原文地址:Inno Setup 安装.卸载前检测进程或服务作者:一去丶二 ...

  6. windows 7 系统进程服务详解

    windows 7已经发布有段时间了,相信很多网友都已经换上了传说中非常完美的win7系统.win7不仅继承而且还超越了vista的美观界面,性能优化方面也下足了功力.还拥有强大的win xp兼容性, ...

  7. widows下的进程与服务

    进程: 当程序卡死的时候,我们可以直接通过任务管理器来关闭进程. 服务: 在这个界面,我们可以选择启动或者关闭相关服务,还可以选择服务是否自动启动. 以关闭MySQL自启动服务为例:https://j ...

  8. windows 删除无用服务

    Windows中无用的服务怎么删除? Windows服务也称为Windows Service,它是Windows操作系统和Windows网络的基础,属于系统核心的一部分,它支持着整个Windows的各 ...

  9. 解读 Windows Azure 存储服务的账单 – 带宽、事务数量,以及容量

    经常有人询问我们,如何估算 Windows Azure 存储服务的成本,以便了解如何更好地构建一个经济有效的应用程序.本文我们将从带宽.事务数量,以及容量这三种存储成本的角度探讨这一问题. 在使用 W ...

随机推荐

  1. Unity3D中的Coroutine详解

    Unity中的coroutine是通过yield expression;来实现的.官方脚本中到处会看到这样的代码. 疑问: yield是什么? Coroutine是什么? unity的coroutin ...

  2. [BZOJ 1303] [CQOI2009] 中位数图 【0.0】

    题目链接:BZOJ - 1303 题目分析 首先,找到 b 的位置 Pos, 然后将数列中小于 b 的值赋为 -1 ,大于 b 的值赋为 1 . 从 b 向左扩展,不断算 Sum[i, b - 1] ...

  3. java interface

  4. C语言宏定义使用技巧

    写好C语言,漂亮的宏定义很重要,使用宏定义可以防止出错,提高可移植性,可读性,方便性 等等.下面列举一些成熟软件中常用得宏定义...... 1.防止一个头文件被重复包含 #ifndef COMDEF_ ...

  5. Struts2接收checkbox的值

    Struts2接收checkbox的值:   HTML: <input type="checkbox" name="ssl" value="B1 ...

  6. 【HDOJ】2363 Cycling

    二分+Dijkstra. #include <iostream> #include <cstdio> #include <cstring> #include < ...

  7. 自己动手实现Queue

    前言: 看到许多面经说,有时候面试官要你自己当场用模板写出自己的vector容器.于是,我也琢磨着怎么自己动手写一个,可是本人才刚刚学C++模板编程不久,会的不多.不过,我恰好在C++ Primer上 ...

  8. bzoj3208

    乍一看感觉好神,仔细一看数据范围…… 什么水题啊,直接暴力就可以了…… ..,..] of longint;     v:..,..] of boolean;     i,j,k,a1,a2,b1,b ...

  9. 数据结构(Splay平衡树): [NOI2007] 项链工厂

    [NOI2007] 项链工厂 ★★★   输入文件:necklace.in   输出文件:necklace.out   简单对比 时间限制:4 s   内存限制:512 MB [问题描述] T公司是一 ...

  10. voronoi