查了N多的资料,也找不到一个添加WMI的空间的例子,找到的都是添加WMI类的例子。
后来微软的人,得到了添加自己创建的wmi名称空间的代码。我们可以在我们自己定义的名称空间下,添加一些wmi类,记录一些信息,供远程wmi读取信息。结合wmi远程调用程序的方法,可以用来客户服务器通讯。
[windows2003 测试通过]
添加wmi名称空间:
仿照windows\system32\wbem下的mof文件,创建一个自己的mof文件放到这个目录里,
使用命令"mofcomp.exe yourfile.mof" 来创建自己的名称空间
使用代码来添加名称空间:
ConnectionOptions options
=
new
ConnectionOptions(); options.Username
=
user;
//
could be in domain\user format
options.Password
=
password; ManagementScope scope
=
new
ManagementScope(
string
.Format(
@"
\\{0}\root
"
,compName), options); ManagementClass Class
=
new
ManagementClass(scope,
new
ManagementPath(
"
__namespace
"
),
new
ObjectGetOptions()); ManagementObject instance
=
Class.CreateInstance(); instance[
"
Name
"
]
=
"
mytest
"
; instance.Put();
注意是为远程Client添加wmi名称空间,如若要给当前系统添加wmi名称空间,则不需要也不能使用ConnetionOption(网络连接)。
添加名称空间后的效果
删除wmi名称空间:
ConnectionOptions options
=
new
ConnectionOptions(); options.Username
=
user;
//
could be in domain\user format
options.Password
=
password; ManagementScope scope
=
new
ManagementScope(
string
.Format(
@"
\\{0}\root
"
,compName), options); ManagementClass Class
=
new
ManagementClass(scope,
new
ManagementPath(
"
__namespace
"
),
new
ObjectGetOptions()); ManagementObject instance
=
Class.CreateInstance(); instance[
"
Name
"
]
=
"
mytest
"
; instance.Delete();
远程执行命令的wmi
ManagementClass win32_process
=
new
ManagementClass(scope,
new
ManagementPath(
"
Win32_process
"
),
null
); ManagementBaseObject inParamaters
=
win32_process.Methods[
"
Create
"
].InParameters; inParamaters[
"
CommandLine
"
]
=
"
c:\app.exe
"
; inParamaters[
"
CurrentDirectory
"
]
=
"
c:\
"
; ManagementBaseObject outParamater
=
win32_process.InvokeMethod(
"
Create
"
, inParamaters,
null
);
//
now wait for the setup program to finish
string
query
=
string
.Format(
"
select * from __instanceDeletionEvent within 2 where targetInstance isa 'win32_process' and targetInstance.ProcessID = {0}
"
, outParamater[
"
ProcessId
"
]); WqlEventQuery q
=
new
WqlEventQuery(query); ManagementEventWatcher w
=
new
ManagementEventWatcher(scope, q,
new
EventWatcherOptions(
null
,
new
TimeSpan(
0
,
0
,
5
,
0
),
1
));
try
{ w.WaitForNextEvent(); }
catch
(Exception e)
{ // Todo: possibly take out this print because it is handled. Console.WriteLine(string.Format("Handled: {0} during test automation installation.", e.Message)); }
转载于:https://www.cnblogs.com/skyfei/archive/2005/04/08/134078.html