且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#在远程计算机上启动和停止Windows服务

更新时间:2022-12-24 15:45:35

检查这个......


 





使用System;

使用System.Management; 

命名空间WMITest

{

class clsMain

{

static void Main( string [] args)

{          

GetWMIStats();

Console.ReadLine();

}



static void GetWMIStats()

{

//远程计算机的连接凭证 -

//登录帐户 必须具有远程机器的管理员访问权限$
ConnectionOptions oConn = new ConnectionOptions();
$
//oConn.Username =" username&quot ;;

//oConn.Password =" password";
$
string remoteMachineName =" localhost";
$
System.Management.ManagementScope oMs = new System.Management.ManagementScope( " \\\\" + remoteMachineName,oConn);     


//使用此特定WQL查询传递要查询的服务名称---

System.Management.RelatedObjectQuery oQuery =

new System.Management.RelatedObjectQuery(" Win32_Service.Name ='Alerter'");

ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,oQuery);
$
ManagementObjectCollection oReturnCollection = oSearcher.Get();  



foreach(管理对象oReturn in oReturnCollection)

{

Console.WriteLine(" Name:" + oReturn [" Name"]。ToString());
$


//对相应的每个属性重复上述过程

//可以读取的对象有关详细信息,请参阅MSDN上的WMI文档。

}  

}

}

}

 


 


Initially I created win application with ServiceController to restart remote windows service, I success to restart remote windows service.

then I implement same code in windows service to restart remote windows service, but it gives some error message like "can not open 'service name' on computer 'machine name'.

In serviceProcessInstaller properties i given like Account = LocalSystem

Note i also check the Service Manager on my local computer and connect it to the remote computer, there i able to restart the service.

then why its not allowing to restart the service from windows service

Please suggest me....

thnaks

 

check this...

 

example:

using System;
using System.Management; 
namespace WMITest
{
class clsMain
{
static void Main(string[] args)
{          
GetWMIStats();
Console.ReadLine();
}

static void GetWMIStats()
{
//Connection credentials to the remote computer -
//logged in account  must have adminstrator access for a remote machine
ConnectionOptions oConn = new ConnectionOptions();
//oConn.Username = "username";
//oConn.Password = "password";
string remoteMachineName="localhost";
System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\" +remoteMachineName , oConn);     
// pass the name of the service to query with this particular WQL query---
System.Management.RelatedObjectQuery oQuery =
new System.Management.RelatedObjectQuery("Win32_Service.Name='Alerter'");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();  

foreach( ManagementObject oReturn in oReturnCollection )
{
Console.WriteLine("Name : " + oReturn["Name"].ToString());

// Repeat the above process for each property of the respective
// object that can be read. See the WMI documentation at MSDN for details.
}  
}
}
}