▣중-고급자 활용/그게 궁금해?

[WSH] WScript 와 CSciprt

횡재수 2008. 7. 26. 03:02

* Windows Script Host Object Model *

 

[WScript]

┣<WshShell>
┃ ┃
┃ ┠ WshShortcut
┃ ┃
┃ ┠ WshUrlShortcut
┃ ┃
┃ ┠ WshEnvironment
┃ ┃
┃ ┠ WshSpecialFolders
┃ ┃
┃ ┖ WshScriptExec


┣<WshArguments>
┃  ┃
┃  ┠ WshNamed
┃  ┃
┃  ┖ WshUnnamed


┣<WshController>
┃  ┃
┃  ┠ WshRemote
┃  ┃
┃  ┖ WshRemoteError


┗<WshNetwork>

 

* WSH Objects *

WSH 관련 작업은 한마디로 개체(object)를 생성하여 그 개체에서 사용가능한

Method 와 Property를 이용하는 것이라고 할 수 있다.

따라서 작업을 하려면 먼저 개체를 생성해야 하고, 가장 상위의 4개 개체는

주개체(Main Object)인 Wscript 개체를 통해 생성된다.

주개체는 기본적으로 생성되는 것으로 따로 생성하고 할 필요가 없다.

(다른 스크립트들과는 달리 WSH에서는 개체의 종류와 생성방법 등이 몇 개로 특정되어 있어

사용하기가 편하다.)

개체도 변수의 일종이므로 개체 생성방법 역시 변수처럼 Dim 으로 변수 선언 후 해당 변수에

CreateObject 로 할당하면 된다.

다만 개체는 변수가 개체변수라는걸 알리기위해 앞에 Set 을 해준다.

 

Wscript

   WSH의 메인 개체(오브젝트)

WshShell
   Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")

WshShortcut
   Dim Link : Set Link = WshShell.CreateShortcut(DeskTop & "\test.lnk")
WshSpecialfolders
   Access any of the Windows Special Folders

   Dim DeskTop : DeskTop = WshShell.SpecialFolders("Desktop") ' or AllUsersDesktop

WshURLShortcut
   Dim URL : Set URL = WshShell.CreateShortcut(DeskTop & "\Go Naver.url")
WshEnvironment
   Dim WshEnv : Set WshEnv = WshShell.Environment("Process")
WshScriptExec
   Dim oExec : Set oExec = WshShell.Exec("calc")
WshArguments
   Dim objArgs : Set objArgs = WScript.Arguments
WshNamed
WshUnnamed
WshNetwork
   Dim Net : Set Net = WScript.CreateObject ("WScript.Network")

WshController
   Dim Controller : Set Controller = WScript.CreateObject("WSHController")

WshRemote
WshRemoteError

 

메인 오브젝트(WScript)의 하위 오브젝트들인 WshShell,WshArguments,WshNetwork,

WshController,WshRemote 등은 메인 오브젝트(WScript)의 method 인 CreateObject 를

통해 생성되고, 각 오브젝트의 하위 오브젝트는 각 오브젝트에서 사용 가능한 적절한

method와 property 의 사용을 통해 생성된다.

 

- WScript : Windows 용

- CScript : cmd 용

 

* CScript 명령줄 사용예 *

 

CScript [host options...][script name][options and parameters]
CScript //nologo C:\Scripts\Qbackup.vbs
 

//?

 

//I               ;  Interactive mode(default). (대화창이나 에러메시지가 윈도에 표시된다)

//B              ;  Batch mode. ( 대화창이나 에러 메시지가 모두 프롬프트창에 표시된다.)

 

//T:nn          ; 타임아웃(일정시간이 지나면 스크립트 실행 중지. 초단위. 기본값은 무제한)

 

//NOLOGO   ; 배너 표시안함(기본값은 표시 ->  //LOGO )

 

//H:CScript   ; CScript.exe 를 스크립트 실행을 위한 기본 호스트로 지정.
//H:WScript   ; WScript.exe 를 스크립트 실행을 위한 기본 호스트로 지정.

; WSH의 기본 스크립트는 레지스트리값을 통해 확인할 수 있다.

; => HKEY_CURRENT_USER\Software\Microsoft\Windows Scripting Host\Settings

 

//S              ; Current User를 위해 현재 명령줄 옵션을 저장.

//E:engine   ; 스크립트를 지정된 스크립트엔진으로 실행.

                    (파일확장자가 달라도 스크립트 실행이 가능)
//D             ; 디버깅 중지.
//X             ; 디버깅하면서 스크립트 실행.
//JOB:   ; .wsf 파일의 특정 JobID 를 실행.
//U             ; Enables you to use Unicode for redirected input/output (I/O) from the console.

 

- Object와 각 Object에 따른 Property -

 

* WScript object's Properties *

 

WScript.Name             '  Windows Script Host
WScript.FullName        '  C:\WINDOWS\System32\wscript.exe
WScript.Version           '  5.6
WScript.BuildVersion    '  8827
WScript.Path                '  CScript.exe or WScript.exe 파일의 경로 -> C:\WINDOWS\system32
WScript.ScriptFullName   '  현재 실행중인 파일의 full path & name -> C:\TEMP\test.vbs
WScript.ScriptName        '  현재 실행중인 파일의 이름 -> test.vbs

WScript.Interactive     ' 모드(interactive or batch) 표시. -> 1  or True

WScript.Interactive = False ' 배치모드로 전환된다.

 

WScript.StdErr
WScript.StdIn
WScript.StdOut

cf, StdIn, StdOut, and StdErr streams 는 CScript.exe 를 통해서만 액세스할 수 있다.

 

WScript.Arguments

WScript.Arguments.Named

WScript.Arguments.Unnamed

WScript.Arguments.Named.Item(이름)

WScript.Arguments.Unnamed.Item(순서)

 

myScript.vbs /c:arg1 /d:arg2

WScript.Arguments.Named.Item("c")   ' ->  arg1

myScript.vbs arg1 arg2

WScript.Arguments.Unnamed.Item(0)   ' ->  arg1  (zero-based index )

 

WScript Object는 기본적으로 생성되는 Object이므로 각 속성들 또한 아무곳에서나 사용가능..

 

* Shortcut object's Properties *

Shortcut Object는 WshShell Object의 CreateShortcut 메서드를 이용해 생성

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
Dim Desktop : Desktop = WshShell.SpecialFolders("Desktop")
Dim objLink : Set objLink = WshShell.CreateShortcut(Desktop & "\ScriptsFolder.lnk")

objLink.TargetPath = WScript.ScriptFullName
objLink.RelativePath = "C:\Scripts\"
objLink.WindowStyle = 1                   ' 1  ->  Activates and displays a window
objLink.Hotkey = "Ctrl+Alt+C"
objLink.IconLocation = "notepad.exe, 0"
objLink.Description = "Shortcut to Script Working Directory"
objLink.WorkingDirectory = Desktop
objLink.Arguments = "C:\myFile.txt"
objLink.Save
WScript.Echo objLink.FullName

 

* TextStream object's Properties *

FSO의 CreateTextFile, OpenTextFile, OpenAsTextStream 등의 Method를 이용해서 생성

AtEndOfLine

AtEndOfStream

Column

Line

Set FSO = CreateObject("Scripting.FileSystemObject")

Set f = FSO.OpenTextFile("c:\testfile.txt", ForReading)

do while f.AtEndOfStream <> True
    Wscript.Echo f.ReadLine
loop

 

* WshRemote object's Properties *

 

Dim Controller : Set Controller = WScript.CreateObject("WSHController")
Dim RemoteScript : Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute
Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

' Staus value :

' 0 : 원격스크립트 생성됨,but 아직 실행안됨

. 1 : 원격스크립트 실행중

' 2 : 원격스크립트 실행 끝남

 

* WshRemoteError object's Properties *

 

Dim RemoteError : Set RemoteError = RemoteScript.Error

RemoteError.Number
RemoteError.Line
RemoteError.Character
RemoteError.Description
RemoteError.Source
RemoteError.SourceText

 

* WshShell object's Properties *

 

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory       '  C:\Temp

 

Dim WshEnv : Set WshEnv = WshShell.Environment("PROCESS")

WScript.Echo WshEnv("NUMBER_OF_PROCESSORS")

 

NUMBER_OF_PROCESSORS
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
OS
COMSPEC
HOMEDRIVE
HOMEPATH
PATH
PATHEXT
PROMPT
SYSTEMDRIVE
SYSTEMROOT
WINDIR
TEMP
TMP

 

Dim Desktop : Desktop = WshShell.SpecialFolders("Desktop")

AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates

 

cf, Environment 나 SpecialFolders property 에 의해 반환되는 객체는 컬렉션 객체이다.

따라서 Itme , count (number of items) 등을 이용할 수 있다.

 

WScript.Echo WshShell.SpecialFolders.Item("Programs")
' ->  C:\Documents and Settings\USER_ID\시작 메뉴\프로그램

 

* WshScriptExec object's Properties *

 

Dim oExec : Set oExec = WshShell.Exec("%comspec% /c dire")

If oExec.ExitCode <> 0 Then
     WScript.Echo "Warning: Non-zero exit code"
End If

' ExitCode : 대상 프로그램이 끝나지 않았으면 0, 끝나면 프로그램에서 반환된 값

 

* WshNetwork object's Properties *

 

Dim Net : Set Net = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & Net.UserDomain
WScript.Echo "Computer Name = " & Net.ComputerName
WScript.Echo "User Name = " & Net.UserName

 

 

Object의 종류와 그에 따른 속성들이 몇 개 안되므로 사용하기 편하다.

 

* WSH Methods index *

 

각 Method 에 대한 자세한 설명은 이 후 예문이 나올 때..

 

AddPrinterConnection
AddWindowsPrinterConnection
AppActivate
Close
ConnectObject
Count
CreateObject
CreateScript
CreateShortcut
DisconnectObject
Echo
EnumNetworkDrives
EnumPrinterConnections
Exec
Execute
Exists
ExpandEnvironmentStrings
GetObject
getResource
LogEvent
MapNetworkDrive
Popup
Quit
Read
ReadAll
ReadLine
RegDelete
RegRead
RegWrite
Remove
RemoveNetworkDrive
RemovePrinterConnection
Run
Save
SendKeys
SetDefaultPrinter
ShowUsage
Sign
SignFile
Skip
SkipLine
Sleep
Terminate  (WshScriptExec)
Verify
VerifyFile
Write
WriteBlankLines
WriteLine

 

아래 상수들은 VBScript에 들어 있으므로 사용하기 전에 정의하지 않아도 된다.

(Value 입력시 Value 대신 Constant 를 바로 사용가능하다는 뜻)

단, MsgBox 반환값은 코드에 명시적으로 상수로 선언해야 사용 가능.

* String Constants *

Constant     Value           Description
vbCr           Chr(13)        캐리지 리턴 (Carriage return)
vbLf            Chr(10)        라인 피드 (linefeed)
vbCrLf         Chr(13) & Chr(10)    캐리지 리턴-라인 피드 조합

vbNewLine  Chr(13) & Chr(10) 또는 Chr(10) 각 플랫폼 특정의 줄 바꿈 문자
vbNullChar   Chr(0)          값이 0인 문자 (Character having the value 0)
vbNullString  값이 0인 문자열.       길이가 0인 문자열("")과 다르며, 외부 프로시저 호출에 사용.
vbTab          Chr(9)        수평 탭 (Horizontal tab)

vbFormFeed    Chr(12)    폼 피드. Microsoft Windows에서는 사용되지 않습니다.
vbVerticalTab  Chr(11)    수직 탭. Microsoft Windows에서는 사용되지 않습니다.

* space(11) : 빈칸 11 개

* 줄바꿈 :
캐리지 리턴 Chr(13), 라인 피드 문자 Chr(10) 또는

캐리지 리턴-라인 피드 문자의 조합 Chr(13) & Chr(10) 을 사용하여 줄을 구분할 수 있다.
Msgbox "첫째 줄입니다. " & Chr(13) & Chr(10) & "둘째 줄입니다"

* 쌍따옴표(double quotation marks) 넣기 : Chr(34) 로 감싸기 or 쌍따옴표 두쌍으로 감싸기
내 이름은 "김팔봉"   ->  "내이름은 " & Chr(34) & "김팔봉" & Chr(34)
내 이름은 "김팔봉"   ->  "내이름은 " & """김팔봉"""

============================

* Tristate Constants *

Constant       Value  Description

vbUseDefault   -2     Use default from computer's regional settings.
vbTrue            -1     True
vbFalse           0      False

============================

* Color Constants *

Constant      Value        Description

vbBlack        &h00         Black
vbRed          &hFF         Red
vbGreen       &hFF00      Green
vbYellow      &hFFFF     Yellow
vbBlue         &hFF0000   Blue
vbMagenta   &hFF00FF   Magenta
vbCyan        &hFFFF00   Cyan
vbWhite        &hFFFFFF  White

============================

* Date and Time Constants *

Constant      Value  Description
vbSunday        1     Sunday
vbMonday       2     Monday
vbTuesday      3     Tuesday
vbWednesday  4     Wednesday
vbThursday     5     Thursday
vbFriday          6     Friday
vbSaturday      7     Saturday

vbUseSystemDayOfWeek 0

Use the day of the week specified in your system settings for the first day of the week.
vbFirstJan1        1  Use the week in which January 1 occurs (default).
vbFirstFourDays 2  Use the first week that has at least four days in the new year.
vbFirstFullWeek  3  Use the first full week of the year.

============================

* Date Format Constants *

Constant      Value  Description
vbGeneralDate  0  Display a date and/or time. ..determined by user system settings.
vbLongDate      1  long date format (specified in user computer's regional settings).
vbShortDate     2  short date format (specified in user computer's regional settings).
vbLongTime     3  long time format (specified in user computer's regional settings).
vbShortTime     4  short time format (specified in user computer's regional settings).

============================

* VarType Constants *

Constant     Value   Description

vbEmpty           0     Uninitialized (default)
vbNull              1     Contains no valid data
vbInteger          2     Integer subtype
vbLong            3     Long subtype
vbSingle          4     Single subtype
vbSingle          5     Double subtype
vbCurrency      6     Currency subtype
vbDate            7      Date subtype
vbString           8     String subtype
vbObject          9     Object
vbError           10     Error subtype
vbBoolean      11     Boolean subtype
vbVariant       12     Variant (used only for arrays of variants)
vbDataObject  13     Data access object
vbDecimal      14     Decimal subtype
vbByte           17     Byte subtype
vbArray       8192     Array

============================

* MsgBox Constants *

Constant              Value   Description
vbOKOnly                 0      Display OK button only.
vbOKCancel             1      Display OK and Cancel buttons.
vbAbortRetryIgnore    2      Display Abort, Retry, and Ignore buttons.
vbYesNoCancel        3      Display Yes, No, and Cancel buttons.
vbYesNo                  4      Display Yes and No buttons.
vbRetryCancel          5      Display Retry and Cancel buttons.
vbCritical                16      Display Critical Message icon.
vbQuestion             32      Display Warning Query icon.
vbExclamation         48      Display Warning Message icon.
vbInformation           64      Display Information Message icon.
vbDefaultButton1        0      First button is the default.
vbDefaultButton2     256      Second button is the default.
vbDefaultButton3     512      Third button is the default.
vbDefaultButton4     768      Fourth button is the default.
vbApplicationModal   0      Application modal.(응답해야 현재 프로그램 계속 실행 가능 )
vbSystemModal     4096     System modal.

cf, 조합이 가능하다

두개버튼(Yes,No) + 물음표 아이콘 + 선택커스의 기본위치가 두번째버튼(No) 인 경우

=> MsgBox "예,아니오 중 선택하세요", vbYesNo + vbQuestion + vbDefaultButton2

=> MsgBox "예,아니오 중 선택하세요", 4 + 32 + 256

=> MsgBox "예,아니오 중 선택하세요", 292


<반환값>

Constant  Value  Description

vbOK          1      OK button was clicked.
vbCancel    2      Cancel button was clicked.
vbAbort       3      Abort button was clicked.
vbRetry       4      Retry button was clicked.
vbIgnore     5      Ignore button was clicked.
vbYes        6      Yes button was clicked.
vbNo          7      No button was clicked.

cf, VBScript 에서 응답값(반환값)은 명시적으로 선언해야 문자열을 상수값으로 사용할 수 있다.

 

intButton = object.Popup (strText,[nSecondsToWait],[strTitle],[nType])

' [] 로 둘러싸인 부분은 옵션이다. (있어도 그만, 없어도 그만)
' cf. 반환값 없이 단독으로 쓰일 때는 괄호를 사용할 수 없다.
' Shell.Popup("안녕하세요", 0, "Hello", vbOkOnly)      =>   괄호로 둘러싸면 에러남..   

 

   - object : WshShell object.

   - strText : 메시지.

   - nSecondsToWait : Optional. 응답 기다릴 시간(second). (생략시 기본값은 0 ,무한정 기다림)
     지정되고 nSecond 동안 응답 없으면..  -> 메시지박스 사라지면서 -1 을 반환한다.

   - strTitle : Optional. 메시지박스 타이틀바에 나타낼 제목.(생략시 "Windows Script Host" )

   - nType : Optional. 버튼과 아이콘 타입.( 생략시 버튼타입은 0 -> vbOkOnly )

   - IntButton : 메시지박스 버튼 클릭시 반환되는 정수값.

=====================================================

 intButton = MsgBox (prompt [, button][, title][, helpfile, context])

 

   - title : 대화 상자의 제목 표시줄에 나타나는 문자식. (생략시 응용 프로그램 이름이 나타남)

   - helpfile, context : 대화상자에 도움말 제공하기위한 도움말 파일들.

      helpfile 이 지정되었다면 context 도 지정되어야 한다.(16bit 에서 사용불가)

 =====================================================

strReturn = InputBox ( prompt[, [title], [default], [xpos], [ypos]])

 

   - cf, 취소 버튼을 클릭하면 zero-length string("") 이 반환된다.

   - MsgBox, InputBox : VBScript 도구로 객체(object) 생성없이 단독으로 바로바로 사용 가능.

=====================================================

 

* Button Types *
Value     Description                             Constants
0           OK                                          vbOkOnly
1           OK, Cancel                              vbOkCancel
2           Abort, Retry, Ignore                   vbAbortRetryIgNore
3           Yes, No, Cancel                       vbYesNoCancel
4           Yes, No                                   vbYesNo
5           Retry, Cancel                           vbRetryCancel

 

* Icon Types *
Value      Description                              Constants
16          Show "Stop Mark" icon.              vbCritical
32          Show "Question Mark" icon.        vbQuestion
48          Show "Exclamation Mark" icon.   vbExclamation
64          Show "Information Mark" icon.     vbInformation

 

* Return value *
Value       Description
-1  <-       timeout(응답시간내 응답 없으면 반환되는 값)
1    <-       OK
2    <-       Cancel
3    <-       Abort
4    <-       Retry
5    <-       Ignore
6    <-       Yes
7    <-       No

cf, 반환값 상수는 명시적으로 상수로 선언해야 사용 가능.