'3. Implementation/VB / Java Script'에 해당되는 글 34건
- 2011.07.28 VBScript/JScript에서 이벤트 핸들러 구현하기
- 2010.10.22 새 창을 열지 않고 Popup 보여주기
- 2010.08.16 [번역] Explaining JavaScript Scope And Closures
- 2010.07.19 WshShell.Exec 사용시 블락되는 문제 해결
- 2010.03.13 VBScript 에서 .NET 클래스 이용하기
- 2010.03.13 IE Automation: VBScript 로 Google 검색하기
- 2010.03.08 명령어상에서 JScript 코드 컴파일하기 - jsc
- 2010.01.23 position:relative 와 position:absolute 을 이용하여 이미지위에 사각형 그리기
- 2009.12.15 Using Automation to Send a Microsoft Outlook Message
- 2009.11.27 How to execute program on remote computer?
- 2009.11.20 [WMI] run an application in a hidden window?
- 2009.10.14 Prevent a Process from Running
- 2009.10.14 Send Email
- 2009.10.14 Show File Open And Save Dialog Box
- 2009.09.25 도스명령어를 실행 하고 그 실행화면 텍스트를 출력하기
- 2009.09.25 [JScript] arguments 속성
- 2009.09.25 [WScript.Shell] SendKeys
- 2009.09.25 List ProgIDs
- 2009.09.25 [WScript.Shell] ExpandEnvironmentStrings - 환경 변수 값 알아내기
- 2009.09.25 [WScript.Shell] Run 과 Exec
VBScript/JScript에서 이벤트 핸들러 구현하기
VBScript
Sub MyObject_Event2(msg) ' ... End Sub
JScript
function MyObject::EvtFcn(arg) { // process event here }
참고: http://groups.google.com/group/microsoft.public.scripting.hosting/browse_thread/thread/be8e470ab5543112/ca516ddc0628889c?q=jscript+connection+point&pli=1
새 창을 열지 않고 Popup 보여주기
#blanket { background-color:#111; opacity: 0.65; filter:alpha(opacity=65); position:absolute; z-index: 9001; top:0px; left:0px; width:100%; } #popUpDiv { position:absolute; background-color:#eeeeee; width:300px; height:300px; z-index: 9002;JavaScript
function toggle(div_id) { var el = document.getElementById(div_id); if ( el.style.display == 'none' ) { el.style.display = 'block';} else {el.style.display = 'none';} } function blanket_size(popUpDivVar) { if (typeof window.innerWidth != 'undefined') { viewportheight = window.innerHeight; } else { viewportheight = document.documentElement.clientHeight; } if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) { blanket_height = viewportheight; } else { if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) { blanket_height = document.body.parentNode.clientHeight; } else { blanket_height = document.body.parentNode.scrollHeight; } } var blanket = document.getElementById('blanket'); blanket.style.height = blanket_height + 'px'; var popUpDiv = document.getElementById(popUpDivVar); popUpDiv_height=blanket_height/2-150;//150 is half popup's height popUpDiv.style.top = popUpDiv_height + 'px'; } function window_pos(popUpDivVar) { if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerHeight; } else { viewportwidth = document.documentElement.clientHeight; } if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) { window_width = viewportwidth; } else { if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) { window_width = document.body.parentNode.clientWidth; } else { window_width = document.body.parentNode.scrollWidth; } } var popUpDiv = document.getElementById(popUpDivVar); window_width=window_width/2-150;//150 is half popup's width popUpDiv.style.left = window_width + 'px'; } function popup(windowname) { blanket_size(windowname); window_pos(windowname); toggle('blanket'); toggle(windowname); }
[번역] Explaining JavaScript Scope And Closures
var monkey = "Gorilla"; function greetVisitor () { return alert("Hello dear blog reader!"); }
function talkDirty () { var saying = "Oh, you little VB lover, you"; return alert(saying); } alert(saying); // Throws an error
function saveName (firstName) { function capitalizeName () { return firstName.toUpperCase(); } var capitalized = capitalizeName(); return capitalized; } alert(saveName("Robert")); // Returns "ROBERT"
function siblings () { var siblings = ["John", "Liza", "Peter"]; function siblingCount () { var siblingsLength = siblings.length; return siblingsLength; } function joinSiblingNames () { return "I have " + siblingCount() + " siblings:\n\n" + siblings.join("\n"); } return joinSiblingNames(); } alert(siblings()); // Outputs "I have 3 siblings: John Liza Peter"
function add (x) { return function (y) { return x + y; }; } var add5 = add(5); var no8 = add5(3); alert(no8); // Returns 8
function add5 (y) { return 5 + y; }
function addLinks () { for (var i=0, link; i<5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function () { alert(i); }; document.body.appendChild(link); } } window.onload = addLinks;
function addLinks () { for (var i=0, link; i<5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function (num) { return function () { alert(num); }; }(i); document.body.appendChild(link); } } window.onload = addLinks;
(function () { var dog = "German Shepherd"; alert(dog); })(); alert(dog); // Returns undefined
var person = function () { // Private var name = "Robert"; return { getName : function () { return name; }, setName : function (newName) { name = newName; } }; }(); alert(person.name); // Undefined alert(person.getName()); // "Robert" person.setName("Robert Nyman"); alert(person.getName()); // "Robert Nyman"
WshShell.Exec 사용시 블락되는 문제 해결
*
* This is a safer, slower, alternative to WshShell.Exec that supports
* retrieving the output (to stdout and stderr) only after the command
* has completed execution. It does not support writing to the standard
* input of the command. It's only redeeming quality is that it will
* not cause deadlocks due to the blocking behavior of attempting to read
* from StdOut/StdErr.
*
* @param cmd The name/path of the command to run
* @param winstyle The window style (see WshShell.Run) of the command, or null
* @return An object with an exitcode property set to the exit code of the
* command, an output property set to the string of text written by the
* command to stdout, and an errors property with the string of text written
* by the command to stderr.
*/
function run(cmd) {
var tmpdir = FSO.GetSpecialFolder(2 /* TemporaryFolder */);
if (!/(\\|\/)$/.test(tmpdir))
tmpdir += "\\";
var outfile = tmpdir + FSO.GetTempName();
var errfile = tmpdir + FSO.GetTempName();
// Note: See KB278411 for this recipe
// Note2: See cmd.exe /? for interesting quoting behavior...
var runcmd = '%comspec% /c "' + cmd + ' > "' + outfile + '" 2> "' + errfile + '""';
var wshexec = WShell.Exec(runcmd);
// Write stuff to the standard input of the command (through cmd.exe)
// Note: This will block until the program exits if significant amounts
// of information are written and not read. But no deadlock will occur.
// Note2: This will error if the program has exited
try {
wshexec.StdIn.Write("stuff\n");
} catch (ex) {
WScript.Echo("Unable to write to program.");
}
// Do stuff, or write more stuff while cmd executes, or wait...
while (wshexec.Status == 0)
WScript.Sleep(100);
exitcode = wshexec.ExitCode;
var output = "";
try {
var outfs = FSO.OpenTextFile(outfile, 1 /* ForReading */);
output = outfs.ReadAll();
outfs.Close();
FSO.DeleteFile(outfile);
} catch (ex) { }
var errors = "";
try {
var errfs = FSO.OpenTextFile(errfile, 1 /* ForReading */);
errors = errfs.ReadAll();
errfs.Close();
FSO.DeleteFile(errfile);
} catch (ex) { }
return { exitcode: exitcode, output: output, errors: errors };
}
result = run("dir");
WScript.Echo("Exit Code: " + result.exitcode);
WScript.Echo("Output:\n" + result.output);
WScript.Echo("Error Output:\n" + result.errors);
VBScript 에서 .NET 클래스 이용하기
HKEY_CLASSES_ROOT 하위의 레지스트리를 보면 아래와 같이 System 으로 시작하는 클래스들을 볼 수 있다.
이러한 .NET Framework 클래스들은 VBScript 에서 생성하여 사용할 수 있다. 이러한 클래스들 중의 일부는 System.ContextMarshalException 클래스와 같이 생성해봐야 아무 쓸모가 없는 것들이 많다.
하지만 그중에는 VBScript 에서 아주 유용하게 사용할 수 있는 것들이 있다.
스크립트에서 정렬을 아이템 하려면 아래와 같이 정렬 함수를 직접 작성해야만 한다.
For i = (UBound(arrNames) - 1) to 0 Step -1 For j= 0 to i If UCase(arrNames(j)) > UCase(arrNames(j+1)) Then strHolder = arrNames(j+1) arrNames(j+1) = arrNames(j) arrNames(j) = strHolder End If Next Next |
하지만 이때 .NET 클래스를 이용하면 아주 쉽게 해결할 수 있다. 아래는 오름차순으로 알파벳을 정렬하는 예이다.
Set DataList = CreateObject _ ("System.Collections.ArrayList") DataList.Add "B" DataList.Add "C" DataList.Add "E" DataList.Add "D" DataList.Add "A" DataList.Sort() For Each strItem in DataList Wscript.Echo strItem Next |
내림차순으로 정렬하는 것 역시 아주 쉽다.
Set DataList = CreateObject _ |
이외에도 Random 수를 생성하는 경우에도 .NET 클래스를 사용할 수 있다.
스크립트상에서 1~100 까지의 수중에서 임의의 수를 생성하는 방법은 아래와 같다.
Randomize Wscript.Echo Int((100 - 1 + 1) * Rnd + 1) |
이를 .NET Framework System.Random.Random 클래스를 사용하면 다음과 같다.
Set objRandom = CreateObject("System.Random") Wscript.Echo objRandom.Next_2(1,100) |
출처 : http://207.46.16.252/en-us/magazine/2007.01.heyscriptingguy.aspx
IE Automation: VBScript 로 Google 검색하기
Search_Google Sub Search_Google() Dim IE Set IE = CreateObject("InternetExplorer.Application") IE.Navigate "http://www.google.com" 'load web page google.com While IE.Busy WScript.Sleep(100) 'wait until IE is done loading page. Wend IE.Document.getElementById("q").Value = "what you want to put in text box" ie.Document.all("btnG").Click 'clicks the button named "btng" which is google's "google search" button While ie.Busy WScript.Sleep(100) 'wait until IE is done loading page. Wend End Sub |
출처 : http://www.vbforums.com/showthread.php?t=512760
참고 : http://msdn.microsoft.com/en-us/magazine/cc337896.aspx
명령어상에서 JScript 코드 컴파일하기 - jsc
To produce an executable JScript program, you must use the command-line compiler, jsc.exe. There are several ways to start the compiler.
If Visual Studio is installed, you can use the Visual Studio Command Prompt to access the compiler from any directory on your machine. The Visual Studio Command Prompt is in the Visual Studio Tools program folder within the Microsoft Visual Studio program group.
As an alternative, you can start the compiler from a Windows command prompt, which is the typical procedure if Visual Studio is not installed.
The Windows Command Prompt
To start the compiler from a Windows command prompt, you must run the application from within its directory or type the fully qualified path to the executable at the command prompt. To override this default behavior, you must modify the PATH environment variable, which enables you to run the compiler from any directory by simply typing the compiler name.
To modify the PATH Environment Variable
-
Use the Windows Search feature to find jsc.exe on your local drive. The exact name of the directory where jsc.exe is located depends on the name and location of the Windows directory and the version of the .NET Framework installed. If you have more than one version of the .NET Framework installed, you must determine which version to use (typically the latest version).
For example, the compiler may be located in C:\WINNT\Microsoft.NET\Framework\v1.0.2914.
-
Right-click the My Computer icon on your Desktop (Windows 2000), and select Properties from the shortcut menu.
-
Select the Advanced tab and click the Environment Variables button.
-
In the System variables pane, select "Path" from the list and click Edit.
-
In the Edit System Variable dialog box, move the cursor to the end of the string in the Variable Value field and type a semicolon (;) followed by the full directory name found in Step 1.
Continuing with the example in Step 1, you would type:
;C:\WINNT\Microsoft.NET\Framework\v1.0.2914
-
Click OK to confirm your edits and close the dialog boxes.
After you change the PATH environment variable, you can run the JScript compiler at the Windows command prompt from any directory on the machine.
Using the Compiler
The command-line compiler has some built-in help. A help screen is displayed by using the /help or /? command-line option or by using the compiler without any options. For example:
jsc /help
There are two ways to use JScript. You can write programs to be compiled from the command line, or you can write programs to be run in ASP.NET.
To compile using jsc
-
At the command prompt, type jsc file.js
The command compiles the program named file.js to produce the executable file named file.exe.
To produce a .dll file using jsc
-
At the command prompt, type jsc /target:library file.js
The command compiles the program named file.js with the /target:library option to produce the library file named file.dll.
To produce an executable with a different name using jsc
-
At the command prompt, type jsc /out:newname.exe file.js
The command compiles the program named file.js with the /out: option to produce the executable named newname.exe.
To compile with debugging information using jsc
-
At the command prompt, type jsc /debug file.js
The command compiles the program named file.js with the /debug option to produce the executable named file.exe and a file named file.pdb that contains debugging information.
There are many more command-line options available for the JScript command-line compiler. For more information, see JScript Compiler Options.
원본 링크 : http://msdn.microsoft.com/en-us/library/7435xtz6%28VS.80%29.aspx
position:relative 와 position:absolute 을 이용하여 이미지위에 사각형 그리기
<html> <STYLE TYPE="text/css"> .attention {color:red}; .test { border-color: red; border-style: solid; border-top-width: 2px; border-bottom-width: 2px; border-left-width: 2px; border-right-width: 2px; }; </STYLE> <body> <div style="position:relative;left:50px;top:30px;height:100px;width:100px"> Some text inside the DIV that will be hidden by the image because the image will be positioned over this flowing text. <img src="sample.gif" style="position:absolute; left:0px; top:0px"> <div style="position:absolute;left:0px; top:0px;width:50px;height:50px" class="test" > </div> <div><br> <table border width="600"> <tr > <td width="300"> <div style="position:relative; " > <img src="sample.gif" style="position:relative; left:0px; top:0px; width:50%" > <!-- <div style="position:absolute;left:0px; top:0px;width:50px;height:50px" class="test" ></div> --> <div> </td> <td width="300"> <div style="position:relative; " > <img src="sample.gif" style="position:relative; left:0px; top:0px; width:50%" > <div style="position:absolute;left:0px; top:0px;width:50px;height:50px" class="test" ></div> <div> </td> </tr> </table> </body> </html> |
아래 코드 역시 참고
<html> <STYLE TYPE="text/css"> .attention {color:red}; .test { border-color: red; border-style: solid; border-top-width: 2px; border-bottom-width: 2px; border-left-width: 2px; border-right-width: 2px; }; </STYLE> <script type="text/javascript"> function getPos(el) { // yay readability for (var lx=0, ly=0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent); return {x: lx,y: ly}; } function test() { var i = getPos(event.srcElement); pos1.innerText = i.x + " " + i.y; } function test2() { var i = getPos(event.srcElement); pos2.innerText = i.x + " " + i.y; } </script> <body> <img src="sample.gif" onload="test()" /> <div id="pos1" ></div> <table> <tr><td>sdf</td><td> <img src="sample.gif" onload="test2()" /> <div id="pos2" ></div> </td></tr></table></body> </html> |
참고 : http://stackoverflow.com/questions/288699/get-the-position-of-a-div-span-tag
How To Find Position of Span Tag
|
참고 : http://aspdotnetcodebook.blogspot.com/2009/03/how-to-find-position-of-span-tag.html
Using Automation to Send a Microsoft Outlook Message
- Outlook 세션 초기화
- 새 메시지 만들기
- 받는 사람 (받는 사람, 참조 및 숨은 참조) 추가하고 해당 이름을 확인하기
- 유효한 속성 (예: 제목, 본문 및 중요도 설정
- (있는 경우 첨부 파일 추가
- 디스플레이/메시지 보내기
- C:\My Documents Customers.txt 라는 예제 텍스트 파일을 만들 폴더.
- Microsoft Access를 시작하고 Northwind.mdb 예제 데이터베이스를 엽니다.
- 모듈 및 형식을 있이 있지 않은 경우 다음 줄에서 해당 선언 섹션에서 만들기: 명시적 옵션
- 도구 메뉴에서 참조를 누릅니다.
- 참조 상자에서 Microsoft Outlook 8.0 개체 모델의 누른 다음 확인을 누릅니다.
참 고: Microsoft Outlook 8.0 개체 모델 사용 가능한 참조 상자가 표시되지 않으면 하드 드라이브의 파일에 대한 찾아보기 Msoutl8.olb. 이 파일을 찾을 수 없으면 이 예제를 계속 진행하기 전에 설치하려면 Microsoft Outlook 설치 프로그램을 실행해야 합니다. - 새 모듈에 다음 프로시저를 입력합니다:
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
' Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Add the CC recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("Michael Suyama")
objOutlookRecip.Type = olCC
' Add the BCC recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("Andrew Fuller")
objOutlookRecip.Type = olBCC
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
' Add attachments to the message.
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
' Resolve each Recipient's name.
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
' Should we display the message before sending?
If DisplayMsg Then
.Display
Else
.Save
.Send
End If
End With
Set objOutlook = Nothing
End Sub
- 이 절차는 테스트하려면 디버그 창에 다음 줄을 입력한 다음 Enter 키를 누릅니다. SendMessage True, "C:\My Documents\Customers.txt"첨부 파일이 있는 Microsoft Outlook에서 새 메시지가 표시된 유의하십시오.
Microsoft Outlook에서 표시하지 않고 메시지를 보내려면 첫 번째 인수에 대해 False 값 사용하는 프로시저 호출:SendMessage False, "C:\My Documents\Customers.txt"첨부 파일을 지정하지 않고 메시지를 보내려면 프로시저를 호출할 때 두 번째 인수를 생략하십시오.SendMessage True
출처 : http://support.microsoft.com/kb/161088
How to execute program on remote computer?
My goal was simple - if I can execute scripts on my computer, then why don't we execute them on remote computers?
I think, this task is very interesting and practical, isn't it? :)
There was one condition. I tried to use "native" Windows solutions, which do not require additional installed software or libraries. I didn't want to use external soft, files, etc.
As a result, I found two solutions. Both of them use WMI:
- Win32_Process Class
- Win32_ScheduledJob Class
Running ahead, I will say that I decided in favour of second solution (Win32_ScheduledJob class).
Let's explore these solutions, and compare them.
For clarity, I will show how to execute simple application (notepad.exe) on remote computer.
Execute program on remote computer with Win32_Process сlass
To create and start new process, I used Create method of the Win32_Process class.
VBScript code is simple enough:
- strComputer = "."
- strCommand = "notepad.exe"
- Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
- Set objProcess = objWMIService.Get("Win32_Process")
- errReturn = objProcess.Create(strCommand, null, null, intProcessID)
- If errReturn = 0 Then
- Wscript.Echo "notepad.exe was started with a process ID: " & intProcessID
- Else
- Wscript.Echo "notepad.exe could not be started due to error: " & errReturn
- End If
String strComputer = "." means "local computer".
So, the result of notepad starting on my local computer was:
And notepad started on my computer! Great!
Then I tried execute my script on remote computer (I set strComputer = "servername"). The result was:
Script said, that the process was created.
Indeed, process was created. It was shown in Task Manager on remote computer:
But I didn't see it on a desktop of remote computer!
Further investigations shown, that:
For security reasons the Win32_Process.Create method cannot be used to start an interactive process remotely.
Win32_Process class is very useful to create and execute batch tasks on remote computer. But it can be applicable for interactive processes.
That's why I preferred the second way. I mean Win32_ScheduledJob сlass.
Execute program on remote computer with Win32_ScheduledJob сlass
By analogy, to create and start new process, I used Create method of the Win32_ScheduledJob class.
VBScript code is :
- strComputer = "."
- strCommand = "notepad.exe"
- Const INTERVAL = "n"
- Const MINUTES = 1
- Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
- Set objScheduledJob = objWMIService.Get("Win32_ScheduledJob")
- Set objSWbemDateTime = CreateObject("WbemScripting.SWbemDateTime")
- objSWbemDateTime.SetVarDate(DateAdd(INTERVAL, MINUTES, Now()))
- errReturn = objScheduledJob.Create(strCommand, objSWbemDateTime.Value, False, 0, 0, True, intJobID)
- If errReturn = 0 Then
- Wscript.Echo "notepad.exe was started with a process ID: " & intJobID
- Else
- Wscript.Echo "notepad.exe could not be started due to error: " & errReturn
- End If
Create method of Win32_ScheduledJob сlass creates new scheduled job on computer. (Hm... Have I said a tautology? :) ) In script I specified the time when scheduled job should be executed - in one minute from now. For that i used standard VBScript function - DateAdd.
Hint: Some time ago I wrote an article abount time/date functions in VBScript. Read it.
The result of execution was excellent! It created scheduled jobs both on local and remote computer.
This is result for remote computer is:
In one minute, the notepad was started and shown on desktop of remote computer!
I was happy :))
I hope, these two methods of remote application execution will be very helpful for you. Computer should calculate, human should think :)
So, I shown how to force your computers to work.
Do you have any ideas on how to force a human to think? :)
Summary:
If you have to run batch tasks, I think first method (Win32_Process Class) is simpler.
If you have to run interactive programs, use Win32_ScheduledJob Class.
--
Dmitry Motevich
From : http://motevich.blogspot.com/2007/11/execute-program-on-remote-computer.html
[WMI] run an application in a hidden window?
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject( _
"winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create( _
"Notepad.exe", null, objConfig, intProcessID)
From MSDn (ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.WIN32COM.v10.en/wmisdk/wmi/wmi_tasks__processes.htm)
Prevent a Process from Running
strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colMonitoredProcesses = objWMIService. _ ExecNotificationQuery("select * from __instancecreationevent " _ & " within 1 where TargetInstance isa 'Win32_Process'") i = 0 Do While i = 0 Set objLatestProcess = colMonitoredProcesses.NextEvent If objLatestProcess.TargetInstance.Name = "notepad.exe" Then objLatestProcess.TargetInstance.Terminate End If Loop |
출처 : Microsoft Script Center
Send Email
Set objEmail = CreateObject("CDO.Message") objEmail.From = "monitor1@fabrikam.com" objEmail.To = "admin1@fabrikam.com" objEmail.Subject = "Atl-dc-01 down" objEmail.Textbody = "Atl-dc-01 is no longer accessible over the network." objEmail.Send |
Send Email without Installing the SMTP Service
Set objEmail = CreateObject("CDO.Message") objEmail.From = "admin1@fabrikam.com" objEmail.To = "admin2@fabrikam.com" objEmail.Subject = "Server down" objEmail.Textbody = "Server1 is no longer accessible over the network." objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ "smarthost" objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 objEmail.Configuration.Fields.Update objEmail.Send |
출처 : Microsoft Script Center
Show File Open And Save Dialog Box
파일 열기 대화상자 (VBScript)
Set objDialog = CreateObject("UserAccounts.CommonDialog") objDialog.Filter = "VBScript Scripts|*.vbs|All Files|*.*" objDialog.FilterIndex = 1 objDialog.InitialDir = "C:\Scripts" intResult = objDialog.ShowOpen If intResult = 0 Then Wscript.Quit Else Wscript.Echo objDialog.FileName End If |
파일 저장 대화상자 (VBScript)
Set objDialog = CreateObject("SAFRCFileDlg.FileSave") objDialog.FileName = "C:\Scripts\Script1.vbs" objDialog.FileType = "VBScript Script" intReturn = objDialog.OpenFileSaveDlg If intReturn Then Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.CreateTextFile(objDialog.FileName) objFile.WriteLine Date objFile.Close Else Wscript.Quit End If |
출처 : Microsoft Script Center 도움말
도스명령어를 실행 하고 그 실행화면 텍스트를 출력하기
var Shell; Shell = new ActiveXObject("WScript.Shell"); var ExecObject = Shell.Exec ("cmd /c dir"); while(ExecObject.status == 0) { WScript.Sleep(100); } var strText = strText = ExecObject.StdOut.ReadAll(); |
[JScript] arguments 속성
arguments 를 사용하면 여러 개의 인수를 처리하는 함수를 만들 수 있다.
다음은 사용 예
function ArgTest(){ var i, s, numargs = arguments.length; s = numargs; if (numargs < 2) s += " ArgTest로 인수 하나가 전달되었습니다. 인수의 내용: "; else s += " ArgTest로 여러 인수가 전달되었습니다. 인수의 내용: " ; for (i = 0; i < numargs; i++) { s += arguments[i] + " "; } return(s); } |
[WScript.Shell] SendKeys
심지어 Ctrl, Alt 키등도 시뮬레이트 할 수 있다. 자세한 내용은 MSDN 을 참고하자.
아래는 코드 예,
var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.Run("calc"); WScript.Sleep(100); WshShell.AppActivate("Calculator"); WScript.Sleep(100); WshShell.SendKeys ("1{+}"); WScript.Sleep(500); WshShell.SendKeys("2"); WScript.Sleep(500); WshShell.SendKeys("~"); WScript.Sleep(500); WshShell.SendKeys("*3"); WScript.Sleep(500); WshShell.SendKeys("~"); WScript.Sleep(2500); |
출처 : http://msdn.microsoft.com/en-us/library/8c6yea83%28VS.85%29.aspx
List ProgIDs
On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery _ ("Select * from Win32_ProgIDSpecification") For Each objItem in colItems Wscript.Echo "Caption: " & objItem.Caption Wscript.Echo "Check ID: " & objItem.CheckID Wscript.Echo "Name: " & objItem.Name Wscript.Echo "Parent: " & objItem.Parent Wscript.Echo "ProgID: " & objItem.ProgID Next |
참고 : http://www.microsoft.com/downloads/details.aspx?FamilyID=B4CB2678-DAFB-4E30-B2DA-B8814FE2DA5A&displaylang=en
[WScript.Shell] ExpandEnvironmentStrings - 환경 변수 값 알아내기
- [Method] ExpandEnvironmentStrings
* 환경변수값 알아내기 *
strReturn = WshShell.ExpandEnvironmentStrings(strString)
- strReturn : an environment variable's expanded value.
- strString : name of the environment variable.
- Remarks :
The ExpandEnvironmentStrings method expands environment variables
defined in the PROCESS environment space only.
'Visual Basic Script
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
//JScript
var WshShell = WScript.CreateObject("WScript.Shell");
WScript.Echo("WinDir is " + WshShell.ExpandEnvironmentStrings("%WinDir%"));
출처 : http://ancdesign.pe.kr/60
[WScript.Shell] Run 과 Exec
- [Method] Run, Exec
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
intError = WshShell.Run (strCommand [, intWindowStyle] [, bWaitOnReturn])
WshShell.Run "%windir%\notepad" & WScript.ScriptFullName
' cf, 반환값 없이 단독 실행시에는 괄호로 묶지 않는다.
intError = WshShell.Run("notepad " & WScript.ScriptFullName, 1, True)
intError = WshShell.Run ("setup.exe", 1, true)
-----------------------------------------------------------------------------------
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
Dim oExec : Set oExec = WshShell.Exec("calc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
WScript.Echo oExec.Status
' Status Return Values
' 0 : The job is still running.
' 1 : The job has completed.
-----------------------------------------------------------------------------------
' Run 과 Exec 의 가장 큰 차이
'=> Run 은 실행만 하지만, Exec는 실행과 동시에 객체(object)를 생성한다.
' 따라서 Exec를 통한 실행은 생성된 객체를 이용한 후속 작업이 용이하다.
Set FSO = Wscript.CreateObject("Scripting.FileSystemObject")
Set Shell = Wscript.CreateObject("Wscript.Shell")
TempName = FSO.GetTempName
TempFile = TempName
Shell.Run "cmd /c ping -n 3 -w 1000 157.59.0.1 >" & TempFile, 0, True
Set TextFile = FSO.OpenTextFile(TempFile, 1)
Do While TextFile.AtEndOfStream <> True
strText = TextFile.ReadLine
If Instr(strText, "Reply") > 0 Then
Wscript.Echo "Reply received."
Exit Do
End If
Loop
TextFile.Close
FSO.DeleteFile(TempFile)
' 아래는 동일한 결과는 가지는 Exec 를 통한 실행이다.
' 실행을 통해 반환되는 StdOut 에 접근하기위해 임시파일 만들고 할 필요가 없다.
Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim ExecObject : Set ExecObject = Shell.Exec ("cmd /c ping -n 3 -w 1000 157.59.0.1")
Do While Not ExecObject.StdOut.AtEndOfStream
strText = ExecObject.StdOut.ReadLine
Loop
출처 : http://ancdesign.pe.kr/60