1 2 /** 3 * @name CeL function for Windows 4 * @fileoverview 5 * 本檔案包含了 Windows 專用的 functions。 6 * @since 7 */ 8 9 10 if (typeof CeL === 'function'){ 11 12 /** 13 * 本 module 之 name(id),<span style="text-decoration:line-through;">不設定時會從呼叫時之 path 取得</span>。 14 * @type String 15 * @constant 16 * @inner 17 * @ignore 18 */ 19 var module_name = 'OS.Windows'; 20 21 //=================================================== 22 /** 23 * 若欲 include 整個 module 時,需囊括之 code。 24 * @type Function 25 * @param {Function} library_namespace namespace of library 26 * @param load_arguments 呼叫時之 argument(s) 27 * @return 28 * @name CeL.OS.Windows 29 * @constant 30 * @inner 31 * @ignore 32 */ 33 var code_for_including = function(library_namespace, load_arguments) { 34 35 // requires 36 if (eval(library_namespace.use_function( 37 'code.compatibility.is_web,code.compatibility.is_HTA'))) 38 return; 39 40 41 /** 42 * null module constructor 43 * @class web 的 functions 44 */ 45 CeL.OS.Windows 46 = function() { 47 // null module constructor 48 }; 49 50 /** 51 * for JSDT: 有 prototype 才會將之當作 Class 52 */ 53 CeL.OS.Windows 54 .prototype = { 55 }; 56 57 58 59 60 //initialization_WScript_Objects(); 61 //initialization_WScript_Objects[generateCode.dLK]='is_web,is_HTA,ScriptHost,dirSp'.split(','); 62 //initialization_WScript_Objects[generateCode.dLK].push('*var args,WshShell,WinShell,WinShell,fso;initialization_WScript_Objects();'); 63 function initialization_WScript_Objects(onlyHTML) { 64 if (typeof library_namespace.WScript === 'object' 65 // && typeof WScript.constructor=='undefined' 66 ) { 67 var i = (ScriptHost = WScript.FullName).lastIndexOf(dirSp); 68 if (i != -1) 69 ScriptHost = ScriptHost.slice(i + 1); 70 WshShell = WScript.CreateObject("WScript.Shell"), WinShell = WScript 71 .CreateObject("Shell.Application"), fso = WScript 72 .CreateObject("Scripting.FileSystemObject"); 73 args = []; 74 for ( var i = 0, a=WScript.Arguments,l = a.length; i < l; i++) 75 args.push(a(i)); 76 } else { 77 if ( // 用 IE 跑不能用 ActiveXObject 78 !(typeof onlyHTML === 'undefined' ? is_web() && !is_HTA() : onlyHTML)// !onlyHTML// 79 && typeof ActiveXObject != 'undefined') 80 try { // 在.hta中typeof WScript=='undefined' 81 // http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/reference/objects/shell/application.asp 82 // http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_intro.asp 83 WshShell = new ActiveXObject("WScript.Shell"), 84 WinShell = new ActiveXObject("Shell.Application"), 85 fso = new ActiveXObject("Scripting.FileSystemObject"); 86 if (is_HTA.HTA) 87 args = is_HTA.HTA.commandLine.split(/\s+/), args.shift(); 88 } catch (e) { 89 } 90 // 判斷假如尚未load則排入以確定是否為HTA 91 else if (is_web(1) && !is_HTA() 92 && !document.getElementsByTagName('body').length) 93 setTimeout('initialization_WScript_Objects();', 9); 94 } 95 96 // if (typeof newXMLHttp == 'function') XMLHttp = newXMLHttp(); 97 98 /* @cc_on 99 @if(@_jscript_version >= 5) 100 // JScript gives us Conditional compilation, we can cope with old IE versions. 101 // and security blocked creation of the objects. 102 ;//else.. 103 @end@*/ 104 105 }; 106 107 108 109 110 111 112 /* 2007/11/17 23:3:53 113 使用 ADSI (Active Directory Service Interface) 存取資料 114 http://support.microsoft.com/kb/234001 115 http://www.dbworld.com.tw/member/article/010328b.htm 116 http://support.microsoft.com/kb/216393 117 */ 118 function addUser(name,pw,group,computer){ 119 // http://msdn.microsoft.com/library/en-us/script56/html/wsmthenumprinterconnections.asp 120 ; 121 // 連上伺服器 122 var oIADs,o; 123 // 利用Create指令,指定產生一個新的使用者類別,以及使用者帳號的名稱。使用SetInfo的指令將目錄服務中的資料更新。 124 try{oIADs=new Enumerator(GetObject(computer='WinNT://'+(computer||(new ActiveXObject('WScript.Network')).ComputerName)));}catch(e){}//WScript.CreateObject('WScript.Network') 125 if(oIADs){//try{ 126 if(name){ 127 try{o=oIADs.Create('user',name);}catch(e){o=new Enumerator(GetObject(computer+'/'+name));} 128 with(o)SetPassword(pw),/*FullName=name,Description=name,*/SetInfo(); 129 // Administrators 130 if(group)(new Enumerator(GetObject(computer+'/'+group))).Add(o.ADsPath); // o.ADsPath: computer+'/'+name 131 return o; // 得到用戶 132 } 133 134 //oIADs.Filter=['user'];//new VBArray('user'); // no use, 改用.AccountDisabled 135 o={}; 136 // http://msdn2.microsoft.com/en-us/library/aa746343.aspx 137 // 對所有的oIADs,通常有Name,Description 138 for(var i,j,a,b,p='Name,AccountDisabled,Description,FullName,HomeDirectory,IsAccountLocked,LastLogin,LoginHours,LoginScript,MaxStorage,PasswordExpirationDate,PasswordMinimumLength,PasswordRequired,Profile'.split(',');!oIADs.atEnd();oIADs.moveNext())if(typeof oIADs.item().AccountDisabled=='boolean'){ 139 for(i=oIADs.item(),j=0,a={};j<p.length;j++)if(b=p[j])try{ 140 a[b]=i[b]; 141 if(typeof a[b]=='date')a[b]=new Date(a[b]); 142 }catch(e){ 143 //alert('addUser():\n['+i.name+'] does not has:\n'+b); 144 // 刪掉沒有的屬性。但僅少數不具有,所以不能全刪。XP中沒有(?):,AccountExpirationDate,BadLoginAddress,BadLoginCount,Department,Division,EmailAddress,EmployeeID,FaxNumber,FirstName,GraceLoginsAllowed,GraceLoginsRemaining,HomePage,Languages,LastFailedLogin,LastLogoff,LastName,LoginWorkstations,Manager,MaxLogins,NamePrefix,NameSuffix,OfficeLocations,OtherName,PasswordLastChanged,Picture,PostalAddresses,PostalCodes,RequireUniquePassword,SeeAlso,TelephoneHome,TelephoneMobile,TelephoneNumber,TelephonePager,Title 145 //p[j]=0;//delete p[j]; 146 } 147 o[i.name]=a; 148 } 149 150 return o; 151 }//catch(e){} 152 }; 153 //a=addUser();for(i in a){d=[];for(j in a[i])d.push(j+': '+a[i][j]);alert(d.join('\n'));} 154 155 156 157 158 159 // 特殊功能 ------------------------------------------------------- 160 161 /* 取得基本環境值 162 // test 163 if(0){ 164 var o=WinEnvironment; 165 if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);} 166 o=SpecialFolder; 167 if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);} 168 o=Network; 169 if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);} 170 o=NetDrive; 171 if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);} 172 o=NetPrinter; 173 if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);} 174 } 175 */ 176 //setTool(); 177 var WinEnvironment,SpecialFolder,Network,NetDrive,NetPrinter; 178 getEnvironment[generateCode.dLK]='WinEnvironment,SpecialFolder,Network,NetDrive,NetPrinter,*getEnvironment();'; 179 function getEnvironment(){ 180 if(typeof WshShell!='object'||typeof SpecialFolder=='object')return; 181 182 WinEnvironment={},Network={},NetDrive={},NetPrinter={}; 183 var i,j,k,o=new Enumerator(WshShell.Environment("Process"));/* Win9x、NT(Administratorもしくはほかのユーザー)の区別なく、すべての場合でエラーが発生しないようにするには、strTypeに"PROCESS"を指定するとよいでしょう。 184 機器上所有已定義的環境變數Windows environment variables http://msdn2.microsoft.com/en-us/library/fd7hxfdd(VS.85).aspx http://www.roy.hi-ho.ne.jp/mutaguchi/wsh/refer/lesson11.htm http://nacelle.info/wsh/03001.php http://www.cs.odu.edu/~wild/windowsNT/Spring00/wsh.htm 185 usual: ALLUSERSPROFILE,APPDATA,BLASTER,CLASSPATH,CLIENTNAME,CommonProgramFiles,COMPUTERNAME,ComSpec,DEVMGR_SHOW_NONPRESENT_DEVICES,HOMEDRIVE,HOMEPATH,INCLUDE,LIB,LOGONSERVER,NUMBER_OF_PROCESSORS,OS,Os2LibPath,Path,PATHEXT,PROCESSOR_ARCHITECTURE,PROCESSOR_IDENTIFIER,PROCESSOR_LEVEL,PROCESSOR_REVISION,ProgramFiles,PROMPT,QTJAVA,SESSIONNAME,SystemDrive,SystemRoot,TEMP,TMP,USERDOMAIN,USERNAME,USERPROFILE,VS71COMNTOOLS,VSCOMNTOOLS,windir,winbootdir 186 187 WshShell.ExpandEnvironmentStrings("%windir%\\notepad.exe"); WshShell.Environment("Process")("TMP") 188 MyShortcut.IconLocation = WSHShell.ExpandEnvironmentStrings("%windir%\\notepad.exe, 0"); 189 190 System HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment 191 User HKEY_CURRENT_USER\Environment 192 Volatile HKEY_CURRENT_USER\Volatile Environment ログオフとともにクリアされる 193 Process, or 98:'WshShell.Environment'==WshShell.Environment("Process"),NT:==WshShell.Environment("System")ただし、Administratorアカウントを持つユーザー以外は、strTypeに"SYSTEM"を指定、もしくは省略するとエラーになります。 194 */ 195 while(!o.atEnd()){ 196 i=o.item(); 197 j=i.indexOf('=');//if((j=i.indexOf('='))!=-1) 198 WinEnvironment[i.slice(0,j)]=i.substr(j+1); // value以';'作為分隔,若有必要可使用.split(';') 199 o.moveNext(); 200 } 201 202 // http://www.microsoft.com/japan/msdn/library/ja/script56/html/wsprospecialfolders.asp HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders 203 // VB中用For Each .. In可列舉出全部,但JS則不行-_-所以得自己列舉 204 // fso.GetSpecialFolder( 0: Windows 文件夾 1: System 文件夾 2: Temp 文件夾 ) 205 setObjValue('SpecialFolder','AllUsersDesktop,AllUsersStartMenu,AllUsersPrograms,AllUsersStartup,AppData,Desktop,Favorites,Fonts,MyDocuments,NetHood,PrintHood,Programs,Recent,SendTo,StartMenu,Startup,Templates'); 206 o=WshShell.SpecialFolders; 207 for(i in SpecialFolder)SpecialFolder[i]=o(i); 208 for(i=0;i<o.Count();i++)SpecialFolder[i]=o.item(i); 209 210 o=new ActiveXObject("WScript.Network");//WScript.CreateObject("WScript.Network"); 211 // http://msdn.microsoft.com/library/en-us/script56/html/wsmthenumprinterconnections.asp 212 Network.ComputerName=o.ComputerName,Network.UserDomain=o.UserDomain,Network.UserName=o.UserName; 213 // Network Drive & Printer mappings 214 j=o.EnumNetworkDrives(),k=1; 215 for(i=0;i<j.Count();i+=2)NetDrive[j.Item(i)?j.Item(i):'Volatile'+k++]=NetDrive[i/2]=j.Item(i+1); 216 j=o.EnumPrinterConnections(),k=1; 217 for(i=0;i<j.Count();i+=2)NetPrinter[j.Item(i)]=NetPrinter[i/2]=j.Item(i+1); 218 }; // function getEnvironment() 219 220 221 222 223 CeL.OS.Windows 224 . 225 /** 226 * 取得 VB 的 Nothing 227 * @returns VB 的 Nothing 228 * @memberOf CeL.OS.Windows 229 */ 230 VBNothing = function () { 231 try { 232 return (new ActiveXObject("ADODB.RecordSet")).ActiveConnection; 233 } catch (e) { 234 } 235 }; 236 237 CeL.OS.Windows 238 . 239 /** 240 * 轉換 VB 的 Safe Array 成為 JS Array. 241 * @param vba VB 的 array 242 * @returns 243 * @memberOf CeL.OS.Windows 244 */ 245 VBA_to_JSA = function (vba) { 246 try { 247 return (new VBArray(vba)).toArray(); 248 } catch (e) { 249 } 250 return []; 251 }; 252 253 CeL.OS.Windows 254 . 255 /** 256 * 轉換JS Array成為VB的Safe Array. 257 * Safe Array To JS Array: plaese use new VBArray(). 258 * JScriptの配列は実際にはCSV文字列だったりする。VBScriptのvartypeに食わせると8(VT_STRING)が返ってくることからもわかる。 259 * @param array 260 * @returns 261 * @see 262 * http://www.microsoft.com/japan/msdn/japan/msdn/library/ja/script56/html/js56jsobjvbarray.asp 263 * @memberOf CeL.OS.Windows 264 */ 265 JSA_to_VBA = function (array) { 266 if (typeof array != 'object') 267 array = [ array ]; 268 var i = 0, dic = new ActiveXObject("Scripting.Dictionary"); 269 for (; i < array.length; i++) 270 dic.add(i, array[i]); 271 return dic.items(); 272 }; 273 274 275 276 277 /* http://www.eggheadcafe.com/forumarchives/scriptingVisualBasicscript/Mar2006/post26047035.asp 278 Application.DoEvents(); 279 */ 280 function DoEvents() { 281 // Triggers screen updates in an HTA... 282 try { 283 if (!DoEvents.w) 284 DoEvents.w = typeof WshShell == 'object' ? WshShell 285 : new ActiveXObject("WScript.Shell"); 286 DoEvents.w.Run("%COMSPEC% /c exit", 0, true); 287 } catch (e) { 288 } 289 } 290 ; 291 var DoNothing = DoEvents; 292 293 function Sleep(_sec) { 294 if (isNaN(_sec) || _sec < 0) 295 _sec = 0; 296 if (typeof WScript == 'object') 297 try { 298 // Win98的JScript沒有WScript.Sleep 299 WScript.Sleep(_sec * 1e3); 300 } catch (e) { 301 } 302 else 303 // if(typeof window!='object') 304 try { 305 if (!Sleep.w) 306 Sleep.w = typeof WshShell == 'object' ? WshShell 307 : new ActiveXObject("WScript.Shell"); 308 Sleep.w.Run(_sec ? "%COMSPEC% /c ping -n " + (1 + _sec) 309 + " 127.0.0.1>nul 2>nul" : "%COMSPEC% /c exit", 0, 310 true); 311 } catch (e) { 312 } 313 }; 314 315 316 317 318 319 /* 320 送key到application http://msdn.microsoft.com/library/en-us/script56/html/wsmthsendkeys.asp 321 SendKeys('a') 送a 322 SendKeys("a{1}4{2}5"); 送a,等1/10s,送4,等2/10s,送5 323 timeOut: <0:loop, 0 or not set:1 time, >0:be the time(ms) 324 */ 325 var SendKeysU; 326 SendKeys[generateCode.dLK]='Sleep'; 327 function SendKeys(keys,appTitle,timeOut,timeInterval){ 328 if(typeof WshShell!='object'||typeof WshShell!='object'&&typeof(WshShell=new ActiveXObject("WScript.Shell"))!='object')return 1; 329 if(isNaN(timeInterval)||timeInterval<1)timeInterval=100; // 時間間隔 330 timeOut=timeOut?timeOut<0?-1:Math.floor(timeOut/timeInterval)+1:0; 331 if(appTitle) 332 while(!WshShell.AppActivate(appTitle)) 333 if(timeOut--)Sleep(timeInterval);else return 2; 334 if(!SendKeysU)SendKeysU=100; // 時間間隔單位 335 while(keys.match(/\{([.\d]+)\}/)){ 336 WshShell.SendKeys(keys.substr(0,RegExp.index)); 337 Sleep(SendKeysU*RegExp.$1); 338 keys=keys.substr(RegExp.lastIndex); 339 } 340 return WshShell.SendKeys(keys); 341 } 342 343 344 345 346 // Create an object reference: hack?! 347 //var windows=new WScript(); 348 // Run the calculator program 349 //windows.explorer.run('calc.exe'); 350 // Writing the local computer name to the screen 351 //document.write(windows.network.computerName); 352 // Copy files from one folder to another 353 //windows.fileSystem.copyFile('c:\\mydocuments\\*.txt', 'c:\\tempfolder\\'); 354 355 356 357 358 359 return ( 360 CeL.OS.Windows 361 ); 362 }; 363 364 //=================================================== 365 366 CeL.setup_module(module_name, code_for_including); 367 368 }; 369