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. etErrorMode(SEM_NOGPFAULTERRORBOX); 去除错误对话框.

    etErrorMode(SEM_NOGPFAULTERRORBOX);  去除错误对话框. http://www.cnblogs.com/-clq/archive/2012/01/22/2328783 ...

  2. bzoj2400

    首先xor类的题目一定要逐位考虑,因为位位之间是不相互影响的逐位考虑每个点是0还是1,这就转化成了一个这样一个问题对于每个点可以选择属于S集合(这位是0)或T集合(这位是1)某些的点对(一条边的两端) ...

  3. 字符串(后缀自动机):Codeforces Round #129 (Div. 1) E.Little Elephant and Strings

    E. Little Elephant and Strings time limit per test 3 seconds memory limit per test 256 megabytes inp ...

  4. 数据结构(线段树):BZOJ 3126: [Usaco2013 Open]Photo

    3126: [Usaco2013 Open]Photo Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 222  Solved: 116 Descrip ...

  5. 【模拟】Codeforces 699B One Bomb

    题目链接: http://codeforces.com/problemset/problem/699/B 题目大意: N*M的图,*代表墙.代表空地.问能否在任意位置(可以是墙上)放一枚炸弹(能炸所在 ...

  6. 差别不在英语水平,而在汉语水平If you do not leave me, we will die together.

    为什么高考语文要提高到180分,英语降到100,差别不在英语水平,而在汉语水平.看下面例句的译法: If you do not leave me, we will die together. 你如果不 ...

  7. svn server安装配置

    安装平台:RHEL5 1.安装软件:httpd.subversion.mod_dav_svn 2.修改配置 修改/etc/httpd/conf.d/subversion.conf.eg: LoadMo ...

  8. [Locked] Smallest Rectangle Enclosing Black Pixels

    An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black ...

  9. 拥有最小高度能自适应高度,IE、FF全兼容的div设置

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " http://www.w3.org/TR/xh ...

  10. 实现O(1)时间复杂度带有min和max 函数的栈

    仅仅是演示实现.不考虑栈使用的数据结构是vector 还是其它容器. 代码例如以下 #include <iostream> #include <vector> using na ...