      1 ﻿
      2 /**
      3  * @name	CeL function for WMI
      4  * @fileoverview
      5  * 本檔案包含了 WMI 的 functions。
      6  * @since
      7  */
      8
      9 if (typeof CeL === 'function'){
     10
     11 /**
     12  * 本 module 之 name(id)，<span style="text-decoration:line-through;">不設定時會從呼叫時之 path 取得</span>。
     13  * @type	String
     14  * @constant
     15  * @inner
     16  * @ignore
     17  */
     18 var module_name = 'OS.Windows.WMI';
     19
     20 //===================================================
     21 /**
     22  * 若欲 include 整個 module 時，需囊括之 code。
     23  * @type	Function
     24  * @param	{Function} library_namespace	namespace of library
     25  * @param	load_arguments	呼叫時之 argument(s)
     26  * @return
     27  * @name	CeL.OS.WMI
     28  * @constant
     29  * @inner
     30  * @ignore
     31  */
     32 var code_for_including = function(library_namespace, load_arguments) {
     33
     34 /**
     35  * null module constructor
     36  * @class	WMI 的 functions
     37  */
     38 CeL.OS.WMI
     39 = function() {
     40 	//	null module constructor
     41 };
     42
     43 /**
     44  * for JSDT: 有 prototype 才會將之當作 Class
     45  */
     46 CeL.OS.WMI
     47 .prototype = {
     48 };
     49
     50
     51
     52
     53
     54
     55
     56 //	WMI set	==================
     57
     58 /*	2007/5/22 23:34:43
     59 	WMI: Windows Management Instrumentation
     60 	http://www.codecomments.com/archive298-2004-5-203306.html
     61 	http://msdn2.microsoft.com/en-us/library/Aa394616
     62 	http://msdn2.microsoft.com/en-us/library/aa389290.aspx
     63 	http://msdn2.microsoft.com/en-us/library/aa389763.aspx
     64 	http://msdn2.microsoft.com/en-us/library/aa393854.aspx	SWbemServices
     65 	http://msdn2.microsoft.com/en-us/library/ms525320.aspx
     66 	http://www.serverwatch.com/tutorials/article.php/1476831
     67 	http://www.serverwatch.com/tutorials/article.php/1476861
     68 	http://www.serverwatch.com/tutorials/article.php/1476871
     69 	http://www.serverwatch.com/tutorials/article.php/1476941
     70
     71 string moniker:
     72 	[[/root/]cimv2:][from[.v]]	[/|\\]root[/|\\]
     73
     74 object moniker:
     75 {
     76 	prefix:'WinMgmts:',	//	moniker prefix
     77 	security:'{impersonationLevel=impersonate}!',
     78 	computer:'.',	//	Computer string(localhost '.')
     79 	p:'cimv2',	//	'/root/' will auto added
     80 	path:'/root/cimv2',	//	Namespace e.g., \root\default
     81
     82 	from:,	//	select from ~
     83 	where:,	//	select from where ~	** You MUST check the string yourself!! This function won't do it!
     84 	v:,	//	value to get
     85 	value:,	//	value used in moniker
     86
     87 	flag:48,	//	flag to call SWbemServices.ExecQuery Method
     88 }
     89
     90 	prefix+security+computer+path+':'+from+'='+value	http://msdn2.microsoft.com/en-us/library/aa389292.aspx
     91
     92 TODO:
     93 多次呼叫最佳化
     94 */
     95 function WMI_data(moniker,func){	//	moniker, for each do function
     96 	var i,oWMIS,_m={
     97 			prefix:'WinMgmts:'
     98 			,security:'{impersonationLevel=impersonate}!'
     99 			,computer:'.'
    100 			,p:'cimv2'
    101 			,path:''
    102 			,from:''
    103 			,value:''
    104 			,v:''
    105 			,flag:48	//	32: wbemFlagForwardOnly + 16: wbemFlagReturnImmediately
    106 	};
    107 	if(!moniker)
    108 		moniker='';
    109
    110 	if(typeof moniker=='string'){
    111 		//	parse moniker
    112 		_m.from=moniker;
    113 		//	取得path
    114 		if(i=_m.from.match(/^([^:]+):([^\/\\]*)$/)){
    115 			if(/^[\/\\]/.test(i[1]))_m.path=i[1];else _m.p=i[1];
    116 			_m.from=i[2];
    117 		}
    118 		//	取得from[.v]
    119 		if(i=_m.from.match(/^([^.]+)\.(.*)$/))_m.from=i[1],_m.v=i[2];
    120 	}else for(i in moniker)_m[i]=moniker[i];
    121
    122 	//	create object
    123 	try{
    124 		//with(_m)alert(prefix+security+'//'+computer+(path||'/root/'+p)+(value||value===0?':'+from+'='+value:''));
    125 		with(_m)oWMIS=GetObject(prefix+security+'//'+computer+(path||'/root/'+p)
    126 				//+(func||v?'':(from?':'+from+(value||value==0?'':'='+value):''))	//	有func||_m.v時無條件捨棄，到後面再搞。
    127 				+(value||value===0?':'+from+'='+value:'')
    128 		);
    129 		//oLoc=new ActiveXObject("WbemScripting.SWbemLocator");oSvc=oLoc.ConnectServer(sComputer||null,"root\\default");oReg=oSvc.Get("StdRegProv");	//	http://msdn.microsoft.com/library/en-us/wmisdk/wmi/swbemobject_execmethod_.asp
    130 	}catch(e){
    131 		return;
    132 		/*	useless?
    133   try{
    134    with(new ActiveXObject("WbemScripting.SWbemLastError"))	//	Error Handling
    135     return {ProviderName:ProviderName,ParameterInfo:ParameterInfo,Operation:Operation,Description:Description};
    136   }catch(_e){throw e;}
    137 		 */
    138 	}
    139 	if(!func&&!_m.from)return oWMIS;
    140
    141 	//	do search
    142 	var oE;
    143 	try{
    144 		//	http://msdn2.microsoft.com/en-us/library/aa393866.aspx
    145 		oE=oWMIS.ExecQuery('Select * From '+_m.from+(_m['where']?' Where '+_m.where:'')
    146 				,'WQL'	//	String that contains the query language to be used. If specified, this value must be "WQL".
    147 				,_m.flag
    148 		);
    149 	}catch(e){
    150 		//	程式庫未登錄。
    151 		//	此時 typeof oWMIS=='object'
    152 		popErr(e,0,'WMI_data: error occurred!');
    153 		//if(438!=(e.number&0xFFFF))return;
    154 		return;	//	return {item:function(){}};	//	or return a object using wbemQueryFlagPrototype
    155 	}
    156 	oE=new Enumerator(oE);	//	wbemFlagForwardOnly:32+wbemFlagReturnImmediately:16
    157 	//if(func)for(;!oE.atEnd()&&!func(oE.item());oE.moveNext());
    158 	if(func)while(!oE.atEnd()&&!func(oE.item()))oE.moveNext();
    159 	else return _m.v||_m.v===0?oE.item()?oE.item()[_m.v]:null:oE;
    160 };
    161
    162 /*	用在將 WMI date 轉成 javascript date, old: WMIDateStringToDate
    163 	http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept04/hey0907.mspx
    164 	http://www.microsoft.com/technet/scriptcenter/resources/qanda/aug05/hey0802.mspx
    165
    166 TODO:
    167 return ms
    168 */
    169 WMI_data.DateStringToDate=function(t){
    170  if(!t)return new Date(0);
    171  var m=(''+t).match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d+)?([+ \-]\d+)?$/);
    172  //	http://msdn2.microsoft.com/en-us/library/474de325.aspx
    173  return m?new Date(m[1],m[2]-1,m[3],m[4],m[5],m[6],m[7]*1e3):t;	//	locale會自己調整
    174 };
    175
    176 /*	用在取得 WMI object 之 property
    177 	http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/other/wmi/
    178 	http://msdn.microsoft.com/en-us/library/aa393741%28VS.85%29.aspx
    179 */
    180 WMI_data.getProperties = function(o, is_VBA, is_Date) {
    181 	var oP = new Enumerator(o.Properties_), ph = {}, p;
    182 	while (!oP.atEnd()) {
    183 		o = p = oP.item();
    184
    185 		if (0 && o.Name === 'IPAddress') {
    186 			alert(p);
    187 			alert('' + p + '\n[' + (typeof p) + ']\n'
    188 					// +(new VBArray(p)).toArray()
    189 					+ Object.prototype.toString.call(p));
    190 			for (var i in p)
    191 				alert('' + Object.prototype.toString.call(p[i]) + '\n' + i + '	' + p[i]);
    192 		}
    193
    194 		// 自動別日期
    195 		if (typeof p == 'object' && /^\d{14}(\.\d+)?([+ \-]\d+)?$/.test('' + p))
    196 			p = this.DateStringToDate(p);
    197 		// 自動別 VBA
    198 		else if (typeof p == 'unknown')
    199 			// from VBA_to_JSA()
    200 			try {
    201 				p = new VBArray(p).toArray();
    202 			} catch (e) {
    203 			}
    204 		;
    205 		ph[o.Name] = p;
    206 		oP.moveNext();
    207 	}
    208
    209 	// o=[];for(p in ph)o.push(p+': '+ph[p]);sl(o.join('\n'));
    210 	return ph;
    211 };
    212
    213
    214
    215 /*	cause error!	requires Windows 2003 DNS
    216 	http://forums.devshed.com/dns-36/dns-through-wmi-in-net-140427.html
    217 	http://www.activexperts.com/activmonitor/windowsmanagement/scripts/networking/dns/server/
    218 	http://www.113317.com/blog/article.asp?id=543
    219 	http://blogs.msdn.com/mpoulson/archive/2006/05/10/594950.aspx
    220 	http://www.ureader.com/message/3258511.aspx
    221 	http://www.scriptinganswers.com/forum/forum_posts.asp?TID=516&PID=3124
    222 if(0){
    223  var qHost='213.22.211.in-addr.arpa',qIP=WMI_data({p:'MicrosoftDNS',from:'MicrosoftDNS_PTRType',where:"OwnerName='"+qHost+"'"}).item();
    224  alert(qIP.RecordData);
    225 }
    226 */
    227
    228
    229
    230
    231 /*
    232 	http://msdn2.microsoft.com/en-us/library/aa394239.aspx
    233 	http://tech.163.com/05/0406/10/1GL8FUG200091589.html
    234
    235 test:
    236 with(getSysInfo())alert(Caption+' '+CSDVersion+' '+OtherTypeDescription+'(SP '+ServicePackMajorVersion+'.'+ServicePackMinorVersion+') [Version '+Version+']'
    237 	+'\nWindowsDirectory: '+WindowsDirectory
    238 	+'\nSystemDirectory: '+SystemDirectory
    239 	+'\nFreePhysicalMemory: '+turnSI(FreePhysicalMemory)+'/'+turnSI(PhysicalMemory)+'B ('+PhysicalMemory+' bytes)'
    240 	+'\nOSLanguage: '+OSLanguage+' (0x'+hex(OSLanguage)+')'	//	http://msdn.microsoft.com/zh-tw/library/system.globalization.cultureinfo%28VS.80%29.aspx
    241 	+'\nCountryCode: '+CountryCode
    242 	+'\nCodeSet: CP'+CodeSet	//	http://en.wikipedia.org/wiki/Code_page	http://msdn.microsoft.com/en-us/library/dd317756%28VS.85%29.aspx
    243 	+'\nLocale: '+Locale
    244 	+'\nCurrentTimeZone: '+gDate(CurrentTimeZone*60*1000)
    245 	+'\nMUILanguages: '+MUILanguages
    246 	+'\nBootUpTime: '+LastBootUpTime.toLocaleString()
    247 	+'\nLocalDateTime: '+LocalDateTime.toLocaleString()
    248 	+'\n系統運行 Uptime: '+gDate(Uptime)//+' ms'
    249 	+'\n系統 counter: '+Timestamp+' s'
    250 	+'\nCSName: '+CSName
    251 	+'\nRegisteredUser: '+RegisteredUser
    252 );WScript.Quit();
    253 */
    254
    255 getSysInfo[generateCode.dLK]='WMI_data';
    256 function getSysInfo(){
    257  var o=WMI_data('Win32_OperatingSystem').item(),r;
    258  with(o)r={
    259 	Caption:o.Caption.replace(/\s+$/,''),	//	系統
    260 	Name:o.Name,
    261 	CSDVersion:o.CSDVersion,
    262 	ServicePackMajorVersion:o.ServicePackMajorVersion||(isNaN(o.ServicePackMajorVersion)?'':0),
    263 	ServicePackMinorVersion:o.ServicePackMinorVersion||(isNaN(o.ServicePackMinorVersion)?'':0),
    264 	OtherTypeDescription:o.OtherTypeDescription||'',
    265 	Version:o.Version,	//	系統版本
    266
    267 	WindowsDirectory:o.WindowsDirectory,
    268 	SystemDirectory:o.SystemDirectory,
    269
    270 	CSName:o.CSName,
    271 	RegisteredUser:o.RegisteredUser,
    272
    273 	CurrentTimeZone:o.CurrentTimeZone,
    274 	//	系統最後一次啟動的時間
    275 	//	see: WMI_data('Win32_PerfRawData_PerfOS_System.SystemUpTime')
    276 	LastBootUpTime : WMI_data.DateStringToDate(o.LastBootUpTime),
    277 	LocalDateTime : WMI_data.DateStringToDate(o.LocalDateTime),
    278 	OSLanguage : o.OSLanguage,
    279 	CountryCode : o.CountryCode,
    280 	CodeSet : o.CodeSet,
    281 	Locale : o.Locale,
    282 	MUILanguages : VBA_to_JSA(o.MUILanguages),
    283
    284 	FreePhysicalMemory : o.FreePhysicalMemory,
    285 	PhysicalMemory : WMI_data('Win32_PhysicalMemory').item().Capacity,
    286
    287 	// ms:	maybe null!
    288 	//	http://msdn2.microsoft.com/en-us/library/aa394272.aspx
    289 	//	http://snippets.dzone.com/posts/show/5472
    290 	Uptime : (WMI_data('Win32_PerfRawData_PerfOS_System.Timestamp_Object')
    291 			- WMI_data('Win32_PerfRawData_PerfOS_System.SystemUpTime')) * 1e3
    292 			/ WMI_data('Win32_PerfRawData_PerfOS_System.Frequency_Object'),
    293 	//	顯示系統當下時間之印記 (NOT Uptime!)	這個運行時間是從性能計數器中獲得的64位整型數，不會出現在49.7天後溢出的情況。
    294 	//	http://www.dx21.com/SCRIPTING/WMI/SUBCLASS.ASP?CID=201
    295 	//	maybe NaN
    296 	Timestamp : WMI_data('Win32_PerfRawData_PerfOS_System.Timestamp_Sys100NS')
    297 				/ WMI_data('Win32_PerfRawData_PerfOS_System.Frequency_Sys100NS')
    298  };
    299  //alert(WMI_data('Win32_PerfRawData_PerfOS_System.Timestamp_Sys100NS')+'/'+WMI_data('Win32_PerfRawData_PerfOS_System.Frequency_Sys100NS'));
    300
    301  if (!r.Uptime)
    302 	 r.Uptime = (new Date() - r.LastBootUpTime);
    303
    304  return r;
    305 };
    306
    307
    308 /*	http://support.microsoft.com/kb/328874/zh-tw
    309 	http://msdn.microsoft.com/en-us/library/aa394520(VS.85).aspx
    310 	http://msdn.microsoft.com/en-us/library/aa390456(VS.85).aspx	http://school.21tx.com/2004/06/16/11568_4.html
    311 	If this method succeeds and the ActivationRequired property is 1 (one), the method returns 0 (zero). Otherwise, the method returns one of the WMI error constants.
    312
    313 TODO:
    314 判別 OS
    315 */
    316 getWinID[generateCode.dLK]='WMI_data';
    317 function getWinID(pKey){
    318  var o=WMI_data('Win32_WindowsProductActivation')
    319 	,WshShell=WScript.CreateObject("WScript.Shell");
    320  if(!o){alert('getWinID: Can not get Win32_WindowsProductActivation!');return;}
    321  o=o.item();
    322  if(o.ActivationRequired){
    323   //	未啟用 Windows 前, 用錯誤序號會出錯
    324   alert('Activation Required.');
    325   return;
    326  }
    327  if(pKey)try{
    328   //	SetProductKey: 修改產品金鑰CD-KEY序號, return 0:OK, else error
    329   var e=o.SetProductKey(pKey.replace(/[\s\-]/g,''));
    330   if(e)throw e;
    331  }catch(e){
    332   alert('Update failed for ['+pKey+']:\n'+e.description);	//	for old version 有可能：無效的操作, 此時需 delete OOBETimer registry value
    333   //	TODO: delete OOBETimer registry value for XP 2600: 針對非 Windows XP SP1 或較新版 Windows XP 使用，來停用 Windows。
    334   //WshShell.RegDelete("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WPAEvents\\OOBETimer");
    335  }
    336  return o.GetInstallationID(pKey);//||pKey;	//	無法以此方法獲得 ID
    337 }
    338
    339 //  ksp:
    340 //alert(getWinID('Q9FDY-483HM-FV6RQ-2YQQQ-FD7J8'));WScript.Quit();
    341
    342 // NTSU
    343 //alert(getWinID('VWPM3-MH7H6-VDDHG-YVR4Y-W38JQ'));WScript.Quit();
    344 //alert(getWinID());
    345
    346 //alert(getSysInfo().Caption)
    347 //WScript.Quit();
    348
    349 /*
    350 http://163.19.54.70/student/SerialNumber.txt	大量授權
    351 Windows XP Professional		VWPM3-MH7H6-VDDHG-YVR4Y-W38JQ
    352 Windows XP Prof, x64 Ed.	FG2Q3-QX4JG-FQMMB-8XXD6-34MRY
    353 Office XP Applications		MXCVH-R3QQG-DMQ2M-KXPVQ-VKD6W
    354 Office XP Suites		PCCKW-J8Y6T-P632P-9KW9P-PK88B
    355 Office 2003 Applications	TF6RQ-TVG9Q-FVV74-GR4CP-2C2MB
    356 Office 2003 Suites		WCMVH-XJGPJ-G9BKC-2KHY9-Y7V36
    357 Office 2007 Applications	FJXGQ-RDQRY-Q2784-D89BP-M4MYJ
    358 Office 2007 Suites		KX3T3-RYFP7-BMPKG-JXTQ2-9HWBJ
    359
    360 DBXYD-TF477-46YM4-W74MH-6YDQ8 (CD)
    361 W2JJW-4KYDP-2YMKW-FX36H-QYVD8 (FILES)
    362
    363 'Microsoft Windows XP Professional 5.1.2600':'VWPM3-MH7H6-VDDHG-YVR4Y-W38JQ'
    364
    365 ksp:
    366 Windows XP Professional		Q9FDY-483HM-FV6RQ-2YQQQ-FD7J8
    367 Windows XP Prof, x64 Ed.	V3PP8-CD446-62H9J-3XHVF-K44F3
    368 Windows Vista 的 KMS 認證方式，請參考	http://www.ks.edu.tw/KSnet_service.html#D
    369 Office XP Suites		F86BJ-8PJWY-4P8QX-89FKF-896DT
    370 Office 2003 Suites		F4RMR-DKBX3-2TV7F-9T8QJ-8MYQ6
    371 Office 2007 Suites		M3JH3-4R8XX-R37F2-8D8H8-CBVD8
    372
    373 高雄市？
    374 Office 2007
    375 W3GCD-YWK98-8F6BG-2CYBY-KVWBJ
    376
    377
    378 以下序號皆為 VLK 大量授權序號：
    379 HCQ9D-TVCWX-X9QRG-J4B2Y-GR2TT
    380 MRX3F-47B9T-2487J-KWKMF-RPWBY
    381 QC986-27D34-6M3TY-JJXP9-TBGMD
    382 CM3HY-26VYW-6JRYC-X66GX-JVY2D
    383 DP7CM-PD6MC-6BKXT-M8JJ6-RPXGJ
    384 F4297-RCWJP-P482C-YY23Y-XH8W3
    385 HH7VV-6P3G9-82TWK-QKJJ3-MXR96
    386
    387
    388
    389 Windows XP Home Edition
    390 x:
    391 BQFBV-9J43J-663WJ-T2VDY-X86HY
    392 VTDBB-QVPCJ-33J2V-B9KV4-W2PBM
    393 DJH7R-4CYKJ-GWYDC-7MXHJ-X9VJY
    394 3GT36-XXFDW-JC676-P4FBF-2G6MJ
    395 DGDGK-XVXWR-XJHYK-3688K-8HXYJ
    396 CX7DD-4GX4Y-BTTR4-H88Y7-GQPWQ
    397 J22CH-K4V7X-4G6H6-66JFG-737TK
    398 CG3BH-RG63P-6H2MR-3DVPT-6WTXJ
    399 JPDR8-7X4G9-Q226K-B7VYR-HFHMD
    400 W888Y-WM6YJ-DJQ27-WRB88-7FG96
    401
    402 */
    403
    404
    405 /*
    406 	Win32_ComputerSystem:
    407 	http://msdn2.microsoft.com/en-us/library/aa394224.aspx
    408
    409 	Win32_NetworkAdapterConfiguration:
    410 	http://msdn2.microsoft.com/en-us/library/aa394217.aspx
    411 	http://www.microsoft.com/china/technet/community/scriptcenter/topics/networking/01_atnc_intro.mspx
    412 	http://www.codeproject.com/vbscript/ipaddress.asp?df=100&forumid=3295&exp=0&select=123580
    413
    414
    415 test:
    416 with(get_net_info())alert(UserName+'\n'+Name+'\n'+Workgroup+'\n'+Domain+'\n'+BootupState);
    417
    418 with(get_net_info(2)){
    419  alert(UserName+'\n'+Name+'\n'+Domain+'\n'+BootupState+'\nAll '+netif.length+' interfaces get');
    420  for(i=0;i<netif.length;i++)with(netif[i])
    421   sl(Caption+'\n'
    422 	+DNSDomain+'\n'
    423 	+DHCPServer+'\n'
    424 	+DNSHostName+'\n'
    425 	+DNSServerSearchOrder+'\n'
    426 	+IPSubnet+'\n'
    427 	+DefaultIPGateway+'\n'
    428 	+IPAddress+'\n'
    429
    430 	+IPEnabled+'\n'
    431 	+DHCPEnabled+'\n'
    432 	+SettingID+'\n'
    433
    434 	+MACAddress
    435 	);
    436 }
    437 WScript.Quit();
    438
    439 */
    440 CeL.OS.WMI
    441 .
    442 /**
    443  * 取得網卡設定的IP地址
    444  * @param type	default type: ip setted interfaces only, 1: all interfaces, 2: 實體 net interfaces(網路卡，無線)
    445  * @returns
    446  * @example
    447  * IP=get_net_info().netif[0].IPAddress[0];
    448  * with(get_net_info())alert(UserName+'\n'+Name+'\n'+Workgroup+'\n'+Domain+'\n'+BootupState);
    449  * @requires	WMI_data,VBA_to_JSA
    450  * @memberOf	CeL.OS.WMI
    451  */
    452 get_net_info = function(type) {
    453 	var r = WMI_data('Win32_ComputerSystem');
    454 	if (!r || !r.item()) {
    455 		r = null;
    456 		throw new Error('Can not get Win32_ComputerSystem!\nIs this old system or the function is limited?');
    457 		r = {};
    458 	} else {
    459 		r =
    460 		// WMI_data({computer:IP||'.',from:'Win32_ComputerSystem'}).item()
    461 		WMI_data.getProperties(r.item());
    462 		if (!r.Workgroup)
    463 			//	Windows 2000 and Windows NT: Workgroup is not available. Domain: If the computer is not part of a domain, then the name of the workgroup is returned.
    464 			r.Workgroup = r.Domain;
    465 	}
    466
    467 /*	waste time
    468  with(WMI_data('Win32_NTDomain').item()){
    469   r.Caption=Caption,r.Description=Description;
    470   if(!r.Name)r.Name=Name;
    471  }
    472 */
    473
    474 	r.netif = [];
    475 	WMI_data(
    476 			{
    477 				from : 'Win32_NetworkAdapterConfiguration',
    478 				where : type === 1 ? ''
    479 						// 這判別法不是很好
    480 						//	DHCPEnabled 與 IPEnabled 可以同時為 TRUE
    481 						: type === 2 ? 'MACAddress!=NULL AND (DHCPEnabled=TRUE OR IPEnabled=TRUE)'// OR IPXEnabled=TRUE
    482 						: 'IPEnabled=TRUE' // 'NetEnabled=True': Vista only code?
    483 			}, function(o) {
    484 				// 在DHCP可能得到兩筆同IP之data.
    485 				// MACAddress: getmac.exe, arp -a, nbtstat -a 192.168.0.1
    486 				r.netif.push(WMI_data.getProperties(o));
    487 			});
    488 	return r;
    489 };
    490
    491
    492
    493 CeL.OS.WMI
    494 .
    495 /**
    496  * get CIDR data
    497  * @param {Number} CIDR	CIDR mask bits, 0~32
    498  * @param {String} IP	IPv4, e.g., 1.2.3.4
    499  * @return	CIDR data
    500  * @since	2010/4/21 22:56:16
    501  * @memberOf	CeL.OS.WMI
    502  */
    503 CIDR_to_IP = function (CIDR, IP) {
    504 	if (isNaN(CIDR) || CIDR < 0 || CIDR > 32)
    505 		return;
    506
    507 	if (typeof IP === 'string')
    508 		IP = IP.split('.');
    509 	else if (!(IP instanceof Array))
    510 		IP = [];
    511
    512 	var i = 0, r = {
    513 		//	geteway IP
    514 		geteway : [],
    515 		//	subnet mask
    516 		mask : [],
    517 		//	wildcard mask
    518 		wildcard : [],
    519 		//	subnet start IP,the entire network
    520 		subnet : [],
    521 		//	subnet end IP, broadcast address
    522 		broadcast : [],
    523 		//	Maximum Addresses, range IP count
    524 		//	.count now = Maximum Subnets
    525 		count : 1 << (32 - CIDR)
    526 	};
    527
    528 	for (; i < 4; i++) {
    529 		if (CIDR > 7) {
    530 			CIDR -= 8;
    531 			r.wildcard[i] = 0;
    532 			r.mask[i] = 255;
    533 			r.subnet[i] = r.broadcast[i] = IP[i] || 0;
    534 		} else if (CIDR) {
    535 			r.broadcast[i] = (IP[i] || 0) | (r.wildcard[i] = CIDR = (1 << (8 - CIDR)) - 1);
    536 			r.subnet[i] = (IP[i] || 0) & (r.mask[i] = 255 - CIDR);
    537 			CIDR = 0;
    538 		} else
    539 			r.broadcast[i] = r.wildcard[i] = 255,
    540 			r.subnet[i] = r.mask[i] = 0;
    541 	}
    542
    543 	if (r.count > 2)
    544 		r.count -= 2;
    545 	r.geteway = r.broadcast.join(',').split(',');
    546 	//	[the entire network, .., geteway, broadcast address]
    547 	r.geteway[3] -= 1;
    548
    549 	//alert(r.geteway + '\n' + r.subnet + '\n' + r.broadcast + '\n' + r.wildcard + '\n' + r.subnet + '\n' + r.count);
    550 	return r;
    551 };
    552
    553
    554 CeL.OS.WMI
    555 .
    556 /**
    557  * 改變網卡的IP地址: change IP, set IP
    558  * @param to_s	IP or {IP:''||[], CIDR:24||.CIDR_notation, Subnet:''||[], DNS:''||[], Gateway:254||[], GatewayOrder:''||[]}
    559  * @param from	IP or netif No.
    560  * @since
    561  * 2009/5/7 0:24:5	加強
    562  * 2010/3/3 10:41:17	a work version
    563  * @see
    564  * <a href="http://msdn.microsoft.com/en-us/library/aa394217%28VS.85%29.aspx" accessdate="2010/3/3 13:15">Win32_NetworkAdapterConfiguration Class (Windows)</a>
    565  * <a href="http://www.yongfa365.com/item/Use-WMi-Change-IP-VBS-yongfa365.html" accessdate="2010/3/3 13:14">通过 WMI 改变网卡的IP地址 ChangeIP.vbs - 柳永法(yongfa365)'Blog</a>
    566  * <a href="http://www.microsoft.com/technet/scriptcenter/topics/networking/01_atnc_intro.mspx">Automating TCP/IP Networking on Clients: Part 1: Introduction</a>
    567  * <a href="http://www.dotblogs.com.tw/PowerHammer/archive/2008/03/24/2060.aspx" accessdate="2010/3/3 13:15">使用 WMI 更改IP、子網路遮罩、閘道、DNS - 強力鎯頭 VB BLOG - 點部落</a>
    568  * Using NetSh.exe (no reboot required): <a href="http://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/tsleft.web+WinBatch/How~To+Change~Ip~Address.txt" accessdate="2010/3/3 13:12">WWW Tech Support/WinBatch/How To\Change Ip Address.txt</a>
    569  * @example
    570  * set_net_info({IP:'163.16.20.212',Gateway:254});
    571  * sl(set_net_info({IP:'163.16.20.30',Gateway:254}));WScript.Quit();
    572  * @requires	WMI_data,VBA_to_JSA,JSArrayToSafeArray,CIDR_to_IP
    573  * @memberOf	CeL.OS.WMI
    574  */
    575 set_net_info = function (to_s, from) {
    576
    577 	var _f = set_net_info, r, count, IPA, i = function(ip) {
    578 		if (!(ip instanceof Array))
    579 			if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(ip = '' + ip))
    580 				ip = [ ip ];
    581 			else
    582 				return;
    583 		return JSArrayToSafeArray(ip);
    584 	};
    585
    586 	if (typeof to_s === 'string'
    587 			&& (r = to_s
    588 					.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\/(\d{1,2}))?$/))) {
    589 		count = r[1];
    590 		to_s = {
    591 			IP : count
    592 		};
    593
    594 		if ((r = r[3]) > 15) {
    595 			r = _.CIDR_to_IP(r, count);
    596 			to_s.Gateway = r.geteway.join('.');
    597 			to_s.Subnet = r.mask.join('.');
    598 		}
    599
    600 	}else if (typeof to_s !== 'object' || to_s instanceof Array)
    601 		// treat as IP
    602 		to_s = {
    603 			IP : to_s
    604 		};
    605
    606 	if (!isNaN(to_s.Gateway))
    607 		to_s.Gateway = (to_s.IP instanceof Array ? to_s.IP.join('.') : to_s.IP)
    608 				.replace(/\d+$/, to_s.Gateway);
    609
    610 	//	SubnetMask: Subnet masks that complement the values in the IPAddress parameter. Example: 255.255.0.0.
    611 	if (!('Subnet' in to_s) || !isNaN(to_s.Subnet)) {
    612 		r = _.CIDR_to_IP(to_s.Subnet || _f.CIDR_notation, to_s.IP);
    613 		to_s.Subnet = r.subnet.join('.');
    614 	}
    615
    616 	//sl('set_net_info:\n[' + from + '] → [' + to_s.IP + '/' + to_s.Subnet + ']\nGateway: [' + to_s.Gateway + ']\nDNS: [' + ('DNS' in to_s ? to_s.DNS : _f.default_DNS) + ']');
    617 	// return -1;
    618
    619 	to_s.Subnet = i(to_s.Subnet);
    620 	to_s.IP = i(to_s.IP);
    621 	to_s.DNS = i('DNS' in to_s ? to_s.DNS : _f.default_DNS);
    622
    623 	if ((to_s.Gateway = i(to_s.Gateway)))
    624 		if (!to_s.GatewayOrder)
    625 			for (i = 1, to_s.GatewayOrder = [ 0 ], r = to_s.Gateway instanceof Array ? to_s.Gateway.length
    626 					: 0; i < r;)
    627 				to_s.GatewayOrder.push(++i);
    628 		else if (!(to_s.GatewayOrder instanceof Array))
    629 			to_s.GatewayOrder = [ to_s.GatewayOrder ];
    630
    631 	r = -1;
    632 	count = 0;
    633 	if (!from)
    634 		from = 0;
    635
    636 	WMI_data(
    637 			{
    638 				from : 'Win32_NetworkAdapterConfiguration',
    639 				// 這判別法不是很好
    640 				//	DHCPEnabled 與 IPEnabled 可以同時為 TRUE
    641 				where : 'MACAddress!=NULL AND (IPEnabled=TRUE OR DHCPEnabled=TRUE)'// OR IPXEnabled=TRUE
    642 			},
    643 			function(o) {
    644 				// alert('Get if: ' + o.Caption + '\n' + from + ',' + count);
    645 				// 通常我們不會設定無線連線
    646 				if(/wireless/i.test(o.Caption))
    647 					return;
    648
    649 				if (isNaN(from) || from === count++) {
    650 				for (i = 0, IPA = from ? VBA_to_JSA(o.IPAddress) : [ 1 ]; i < IPA.length; i++) {
    651 					if (!from || IPA[i] === from) {
    652 						r = typeof to_s.IP === 'undefined' ? o.EnableDHCP()
    653 								: o
    654 										.EnableStatic(
    655 												to_s.IP,
    656 												typeof to_s.Subnet === 'undefined' ? o.IPSubnet
    657 														: to_s.Subnet)
    658 										|| typeof to_s.Gateway !== 'undefined'
    659 										&& o.SetGateways(to_s.Gateway,
    660 												to_s.GatewayOrder)
    661 										|| typeof to_s.DNS !== 'undefined'
    662 										&& o.SetDNSServerSearchOrder(to_s.DNS);
    663 						//alert('Set if:\n'+o.Caption+'\nto: '+to_s.IP+'\nerrno: '+r);
    664 							// TODO: error detection
    665 							return 1;
    666 						}
    667 					}
    668 				}
    669 			});
    670
    671 	// not found / error
    672 	// http://msdn.microsoft.com/en-us/library/aa390383%28VS.85%29.aspx
    673 	return r;
    674 };
    675
    676 CeL.OS.WMI
    677 .
    678 // default DNS
    679 // 168.95.1.1,8.8.4.4
    680 set_net_info.default_DNS = '8.8.8.8';
    681
    682 CeL.OS.WMI
    683 .
    684 // http://en.wikipedia.org/wiki/CIDR_notation
    685 set_net_info.CIDR_notation = 24;
    686
    687
    688
    689
    690
    691 /*	get IP of Windows Host
    692 	http://www.scriptinganswers.com/forum/forum_posts.asp?TID=516&PID=3124
    693 	Wscript.Network
    694
    695 ping:
    696 	http://blog.blueshop.com.tw/hammerchou/archive/2006/07/08/32205.aspx
    697 1.
    698 GetObject("winmgmts:").Get("NetDiagnostics=@").Ping(strAddr, Ping)
    699 2.
    700 objCls = GetObject("winmgmts:\\" & strMachine & "\root\CIMV2").Get("NetDiagnostics")
    701 objInPara = objCls.Methods_("Ping").inParameters.SpawnInstance_()
    702 objInPara.Properties_("sInAddr") = "www.google.com.tw" // 設定 Ping 的位置
    703 // Ping 為 方法 , ExecMethod 為 執行方法 ( 把參數送入執行 )
    704 objOutPara = objWMIsvc.ExecMethod("NetDiagnostics=@", "Ping", objInPara)
    705 // 取回輸出參數 ( Ping 的結果 ): objOutPara.ReturnValue = True 則 Ping 成功 , 反之則失敗
    706 objOutPara.sOutArg
    707
    708
    709 test:
    710 var h='Public',ip=getIPofHost(h);alert(ip?h+':\n'+ip:'Computer [\\'+h+'] is unreachable!');
    711
    712 */
    713 //getIPofHost[generateCode.dLK]='WMI_data';
    714 function getIPofHost(h) {
    715 	var qIP = WMI_data( {
    716 		from : 'Win32_PingStatus',
    717 		where : "Address='" + h + "'"
    718 	}).item();
    719 	if (!qIP.StatusCode && qIP.StatusCode != null)
    720 		return qIP.ProtocolAddress;
    721 }
    722
    723 //	終止進程	http://msdn2.microsoft.com/en-us/library/aa393907.aspx
    724 //killProcess[generateCode.dLK]='WMI_data';
    725 function killProcess(n, isPID) {
    726 	var k = 0;
    727 	if (typeof isPID == 'undefined')
    728 		isPID = !isNaN(n);
    729 	WMI_data('Win32_Process', function(p) {
    730 		with (p)
    731 		if (isPID)
    732 			if (ProcessId == n) {
    733 				Terminate();
    734 				k = 1;
    735 				return 1;
    736 			} else if (Caption == n)
    737 				Terminate(), k++;
    738 	});
    739 	return k;
    740 }
    741
    742
    743 /*	列舉進程	http://msdn2.microsoft.com/en-us/library/aa394372.aspx
    744
    745 test:
    746 alert(get_process()['explorer.exe'].CommandLine);
    747 for(i=0,p=get_process();i<p.length;i++)with(p[i])
    748  alert(i+' / '+p.length+'\n['+ProcessId+'] '+Caption+(Name==Caption?'':' ('+Name+')')+'\n'+(Description==Caption?'':Description+'\n')+CSName+'\n'
    749 	+'Open files: '+HandleCount+'\n'
    750 	//+OSName+'\n'
    751 	+'memory: '+MinimumWorkingSetSize+'-'+MaximumWorkingSetSize+'\n'	//	memory pages visible to the process in physical RAM
    752 	+'Time in kernel mode: '+KernelModeTime+' ms\n'+ExecutablePath+'\n'+CommandLine+'\n'+CreationDate.toLocaleString()
    753 	);
    754 */
    755 //get_process[generateCode.dLK]='WMI_data';
    756 function get_process() {
    757 	var r = [];
    758 	WMI_data('Win32_Process', function(p) {
    759 		with (p)
    760 		r[Caption] = r[r.push( {
    761 			ProcessId : ProcessId,
    762 			Caption : Caption,
    763 			ExecutablePath : ExecutablePath,
    764 			CommandLine : CommandLine,
    765 			Name : Name, // ==Caption
    766 			Description : Description, // ==Caption
    767 			CSName : CSName,
    768 			HandleCount : HandleCount,
    769 			OSName : OSName,
    770 			MinimumWorkingSetSize : MinimumWorkingSetSize,
    771 			MaximumWorkingSetSize : MaximumWorkingSetSize,
    772 			KernelModeTime : p.KernelModeTime / 1e5, //	100000ms
    773 			CreationDate : WMI_data
    774 			.DateStringToDate(CreationDate)
    775 		}) - 1];
    776 	});
    777 	return r;
    778 }
    779
    780
    781
    782 /*	列舉服務
    783 	http://msdn2.microsoft.com/en-us/library/aa394418.aspx
    784 	http://www.microsoft.com/taiwan/technet/scriptcenter/topics/vista/indexer.mspx
    785
    786 test:
    787 alert(get_service()['Event Log'].Description);
    788 for(i=0,s=get_service();i<s.length;i++){t=i+' / '+s.length;for(j in s[i])t+='\n'+j+': '+s[i][j];alert(t);}
    789 */
    790 //get_service[generateCode.dLK]='WMI_data';
    791 function get_service() {
    792 	var r = [];
    793 	WMI_data('Win32_Service', function(s) {
    794 		with (s)
    795 		r[Caption] = r[r.push( {
    796 			AcceptPause : AcceptPause,
    797 			AcceptStop : AcceptStop,
    798 			Caption : Caption,
    799 			Description : Description,
    800 			DisplayName : DisplayName,
    801 			ExitCode : ExitCode,
    802 			InstallDate : WMI_data.DateStringToDate(InstallDate),
    803 			Name : Name,
    804 			Pathname : Pathname,
    805 			ProcessId : ProcessId,
    806 			ServiceSpecificExitCode : ServiceSpecificExitCode,
    807 			Started : Started,
    808 			StartMode : StartMode,
    809 			StartName : StartName,
    810 			State : State,
    811 			Status : Status,
    812 			SystemName : SystemName
    813 		}) - 1];
    814 	});
    815 	return r;
    816 }
    817
    818
    819 /*	http://msdn.microsoft.com/en-us/library/bb774148.aspx
    820 WinShell.ShellExecute(appName, appArgs, appPath, "", 0);	http://msdn.microsoft.com/en-us/library/bb774148.aspx
    821 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
    822 <object runat="server" id="WinShell" scope="page" classid="clsid:13709620-C279-11CE-A49E-444553540000"></object>
    823 <object runat="server" id="fso" scope="page" classid="clsid:0D43FE01-F093-11CF-8940-00A0C9054228"></object>
    824
    825 http://windowssdk.msdn.microsoft.com/en-us/library/ms630425.aspx
    826 WinShell.ShutdownWindows();	//	Open the Shutdown dialog	http://www.robvanderwoude.com/index.html
    827 */
    828
    829
    830 /*	2008/8/8 18:29:44
    831 	run them with administrator rights	runs under administrator privileges.
    832 帳戶控制	Windows Vista：使用軟體限制原則對抗未授權的軟體	http://www.microsoft.com/taiwan/technet/windowsvista/security/rstrplcy.mspx
    833 http://4sysops.com/archives/vista%E2%80%99s-uac-how-to-elevate-scripts-vbscript-and-jscript/
    834 http://blogs.msdn.com/aaron_margosis/archive/2007/07/01/scripting-elevation-on-vista.aspx
    835 Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA	c:\windows\system32\control.exe /name Microsoft.UserAccounts	http://www.dashken.net/index.php?/archives/280-VBScript-Check-if-OS-is-Vista-and-Vistas-UAC-status.html
    836 http://msdn.microsoft.com/en-us/magazine/cc163486.aspx
    837 HKEY_LOCAL_MACHINESOFTWARE MicrosoftWindowsCurrentVersionPoliciesSystem\ConsentPromptBehaviorAdmin	http://hsu.easynow.com.tw/index.php?load=read&id=28
    838 http://vistavitals.blogspot.com/2008/02/logon-scripts-token-effort.html
    839 runas	http://www.merawindows.com/Forums/tabid/324/forumid/82/postid/32458/scope/posts/Default.aspx
    840 	http://www.winhelponline.com/articles/185/1/VBScripts-and-UAC-elevation.html
    841
    842 http://forums.techarena.in/vista-security/654643.htm
    843 Set objShell = CreateObject("Shell.Application")
    844 Set objFolder = objShell.Namespace("C:\")
    845 Set objFolderItem = objFolder.ParseName("myhta.hta")
    846 objFolderItem.InvokeVerb "runas"
    847
    848 var WinShell=new ActiveXObject("Shell.Application"),p=location.pathname.replace(/[^\\]+$/,''),o=WinShell.Namespace(p).ParseName(location.pathname.slice(p.length));
    849 o.InvokeVerb("runas");
    850
    851 http://www.zaoxue.com/article/tech-28339_2.htm	http://www.lob.cn/vbs/20071126203237.shtml
    852
    853 TODO:
    854 對 prompt 回應不允許時的處理: 若想在受限的情況下使用?
    855 不使用自訂程式	http://msdn.microsoft.com/en-us/library/bb776820(VS.85).aspx
    856 */
    857 function runas(p){
    858  if(!p)p=typeof WScript=='object'?WScript.ScriptFullName:unescape(location.pathname);
    859  var a={js:'wscript.exe',vbs:'wscript.exe',hta:'mshta.exe'},ext=p.match(/([^.]+)$/);
    860  a=ext&&((ext=ext[1].toLowerCase()) in a)?a[ext]:'';
    861  //	判斷是否有權限
    862  if(!registryF.checkAccess('HKLM\\SOFTWARE\\')){
    863   //	以管理者權限另外執行新的	It will get the UAC prompt if this feature is not disabled.
    864   new ActiveXObject("Shell.Application").ShellExecute(a||p,a?p:'','','runas'/*,5*/);
    865   //	執行完本身則退出
    866   if(typeof WScript=='object')WScript.Quit();else if(typeof window=='object')window.close();
    867  }
    868 }
    869
    870
    871 /*	JScript file: check owner, .exe file
    872 	http://www.microsoft.com/taiwan/technet/scriptcenter/resources/qanda/nov04/hey1115.mspx
    873 	Exec Method (Windows Script Host)	http://msdn.microsoft.com/en-us/library/ateytk4a(VS.85).aspx
    874
    875 usage:
    876 runProg(path): use WshShell.Exec, return [StdOut, StdErr, ExitCode]
    877 runProg(path, 1): use WshShell.Exec, can get output by .StdOut.ReadAll(), or .StdErr.ReadAll()
    878 runProg([path, WindowStyle, WaitonReturn],2): use WshShell.Run
    879 runProg(script path, remote computer): use WshRemote
    880 runProg(path, remote computer): use WMI
    881
    882 TODO:
    883 runProg([path, Verb],3): use Shell.Application InvokeVerb
    884 runProg([path, arg1, arg2,..]): use Shell.Application.ShellExecute
    885
    886
    887 example:
    888 WScript.Echo(runProg('%COMSPEC% /U /c ""C:\\Program Files\\WinRAR\\Rar.exe" vt -scuc "F:\\CLAMP 01.rar""')[0]);
    889
    890
    891 WshShell.Run(command, [WindowStyle 0-10], [WaitonReturn false: nowait & return 0, true: wait & return error code])
    892 WshShell.Exec(),objFolderItem.InvokeVerb()
    893 WshShell.Run('command /k ' + ドライブ +' | cd /D '+ パス);// cd で他ドライブへ移れないので。
    894 */
    895 //runProg[generateCode.dLK]='initWScriptObj';
    896 function runProg(p,r){try{
    897  var s;
    898  if(!r||r===1||r===2)if(typeof (s=new ActiveXObject('WScript.Shell'))=='object'){
    899   if(typeof p=='object'&&r===2)
    900    r=s.Run(p[0],p[1],p[2]);
    901   else if(s=s.Exec(p),r)r=s;
    902   else with(s){
    903    while(!Status)WScript.Sleep(80);
    904    r=[StdOut.ReadAll(),StdErr.ReadAll(),ExitCode];
    905   }
    906   return r;
    907  }else return;
    908
    909  if(/^[^ ]+\.(j|vb)s$/i.test(p)){
    910   s=(WScript.CreateObject('WSHController')).CreateScript(p,r);
    911   s.Execute();
    912   return s;
    913  }
    914
    915  s=GetObject("winmgmts:{impersonationLevel=impersonate}//"+(r||'.')+"/root/cimv2:Win32_Process");
    916  //if(/^[^ ]+\.(j|vb)s$/i.test(p))p="wscript.exe "+p;
    917  return s.Create(p/*,null,null,intProcessID*/);	//	Create 方法會讓這個指令碼在「遠端電腦」上執行。
    918 }catch(e){
    919  //popErr(e);
    920  return e;
    921 }}	//	function runProg
    922
    923
    924
    925 /*	shutdown/reboot computer	2007/5/8-9 0:8:52
    926 	http://www.robvanderwoude.com/index.html
    927 	http://www.ericphelps.com/batch/samples/reboot.txt
    928
    929 	http://www.semcase.com/docus/iis/prog_wmi_tut_03_01.htm	http://www.semcase.com/docus/iis/iis.htm
    930 	http://support.microsoft.com/kb/913538	當您使用會讓列舉程式物件在 Microsoft Windows Server 2003 或 Microsoft Windows XP 用戶端電腦上進行內部複製的 Windows Management Instrumentation (WMI) 功能時，列舉程式物件於用戶端電腦尚未完成使用列舉程式物件的動作時，即遭取消。此外，WMI 功能還可能傳回錯誤碼。
    931
    932 mode:
    933 0	poweroff (if supported by the hardware)
    934 null,1	reboot
    935 	restart
    936 	logoff
    937 	shutdown
    938 	suspend, sleep, hibernate
    939 	lock
    940 //	standby	http://www.tutorials-xe.com/SCRIPTING/Restart-service/
    941 16	force
    942
    943 	open the shutdown dialog
    944
    945 time: seconds
    946 */
    947 var shutdownF;
    948 setObjValue('shutdownF','poweroff,reboot,restart,logoff,shutdown,suspend,lock,force=16,dialog=32',1);
    949 shutdown[generateCode.dLK]='initWScriptObj,shutdownF,Sleep';
    950 function shutdown(mode,time/*,message*/){
    951  if(isNaN(mode))mode=shutdownF.reboot;
    952
    953  var f,sComputer="."
    954 	,_s,s=function(t){
    955 		if(t)return _s;
    956 		if(time&&!_s)Sleep(time);
    957 		_s=1;
    958 	}
    959 	,force=mode&shutdownF.force
    960 	,sF=function(a){f={};for(i=0;i<a.length;i+=2)f[a[i]]=a[i+1];}
    961 	,oWMIS
    962 	;
    963
    964  if((mode-=force)==shutdownF.dialog)try{
    965   s();
    966   WinShell.ShutdownWindows();
    967   return;
    968  }catch(e){}
    969
    970  // way 1: WMI
    971  sF([0,0,shutdownF.logoff,0,shutdownF.shutdown,1,shutdownF.reboot,2,shutdownF.force,4,shutdownF.poweroff,8]);
    972  if(mode in f)try{	//	f.hasOwnProperty(mode)
    973   f=f[mode]&f[force];
    974   oWMIS=new Enumerator(
    975 	 GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}//"+(sComputer||'.')+"/root/cimv2")
    976 	 .ExecQuery("Select * from Win32_OperatingSystem")//Select * from Win32_OperatingSystem Where primary=true
    977 	);
    978   if(!oWMIS)throw 1;
    979   s();
    980   for(;!oWMIS.atEnd();oWMIS.moveNext()){
    981    //oWMIS.item().Reboot();//.Shutdown();	//	force!
    982    oWMIS.item().Win32Shutdown(f);//if()	//	http://msdn2.microsoft.com/en-us/library/aa394058.aspx
    983   }
    984   return;
    985  }catch(e){}
    986  // way 2: RUNDLL32 SHELL32.DLL, SHExitWindowsEx [n]
    987  if(mode in f)try{WshShell.Run(" RUNDLL32 SHELL32.DLL,SHExitWindowsEx "+f[mode]);return;}catch(e){}
    988
    989  // way 3: shutdown.exe utility
    990  sF([shutdownF.logoff,'l',shutdownF.poweroff,'s',shutdownF.shutdown,'s',shutdownF.reboot,'r',shutdownF.dialog,'i']);
    991  if(mode in f)try{WshShell.Run('%windir%\System32\shutdown.exe -'+f+(!time||s(1)?'':' -t '+time)+(force?' -f':''));return;}catch(e){}	//	-s or -r
    992
    993  // way 4: rundll.exe
    994  sF([shutdownF.logoff,'SHELL.DLL,RestartDialog',shutdownF.poweroff,'USER.EXE,ExitWindows',shutdownF.shutdown,'USER.EXE,ExitWindows'/*'USER.EXE,#7'||'USER.EXE, #7'||'USER.EXE,#7 0'*/,shutdownF.restart,'USER.EXE,ExitWindowsExec'/*'USER.EXE,#246'*/]);
    995  if(mode in f)try{WshShell.Run("rundll.exe "+f[mode]);return;}catch(e){}
    996
    997  // way 5: rundll32.exe
    998  sF([shutdownF.poweroff,'KRNL386.EXE,exitkernel',shutdownF.shutdown,'USER.EXE,ExitWindows',shutdownF.suspend,'PowrProf.dll,SetSuspendState']);
    999  if(mode in f)try{WshShell.Run("rundll32.exe "+f[mode]);return;}catch(e){}
    1000  // way 6: RUNDLL32 USER32.DLL
    1001  sF([shutdownF.lock,'LockWorkStation',shutdownF.logoff,'ExitWindowsEx']);
    1002  if(mode in f)try{WshShell.Run("rundll32.exe user32.dll,"+f[mode]);return;}catch(e){}
    1003
    1004  // way 7: RUNONCE.EXE	runonce.exe是微軟Run Once的包裝。它用於第三方應用程序的安裝程序。它允許安裝程序添加到啟動項中，用於再次啟動後，進行進一步配置。
    1005  if(mode==shutdownF.reboot)try{WshShell.Run("RUNONCE.EXE -q");return;}catch(e){}
    1006
    1007  return 1;
    1008 }
    1009
    1010
    1011 //	↑WMI set	==================
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019 return (
    1020 	CeL.OS.WMI
    1021 );
    1022 };
    1023
    1024 //===================================================
    1025
    1026 CeL.setup_module(module_name, code_for_including);
    1027
    1028 };
    1029