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. hadoop job执行完的统计信息

    Total committed heap usage (bytes)= Physical memory (bytes) snapshot= Virtual memory (bytes) snapsho ...

  2. Robot Motion

    Description A robot has been programmed to follow the instructions in its path. Instructions for the ...

  3. Tiling(递推+大数)

    Description In how many ways can you tile a 2xn rectangle by 2x1 or 2x2 tiles? Here is a sample tili ...

  4. Android Wear开发 - 数据通讯 - 第一节 : 连接数据层

    http://developer.android.com/training/wearables/data-layer/accessing.html Accessing the Wearable Dat ...

  5. chage命令管理用户口令时效

    http://zhumeng8337797.blog.163.com/blog/static/1007689142011824102827487/ http://www.th7.cn/system/l ...

  6. Construct Binary Tree from Preorder and Inorder Traversal——LeetCode

    Given preorder and inorder traversal of a tree, construct the binary tree. 题目大意:给定一个二叉树的前序和中序序列,构建出这 ...

  7. wcf系列学习5天速成——第三天 分布性事务的使用 有时间再验证下 不同库的操作

    原文地址:http://www.cnblogs.com/huangxincheng/archive/2011/11/06/2238273.html 今天是速成的第三天,再分享一下WCF中比较常用的一种 ...

  8. 数据库系统概论 SQL

    --(一)创建教材学生-课程数据库 create database s_c go use s_c go --建立“学生”表Student,学号是主码,姓名取值唯一. CREATE TABLE Stud ...

  9. ovs router

  10. CodeForces 27D - Ring Road 2 构图2-sat..并输出选择方案

        题意             n个数1~n按顺序围成一个圈...现在在某些两点间加边..边可以加在圈内或者圈外..问是否会发生冲突?如果不发生冲突..输每一条边是放圈内还是圈外.     题解 ...