Computer/ASP

Wscripting

알찬돌삐 2012. 8. 10. 16:37

* 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:<JobID>   ; .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, 반환값 상수는 명시적으로 상수로 선언해야 사용 가능.


 

>예문 보기


 

>접기

 

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

Return = WshShell.RegRead(strRegName)

Return = WshShell.RegRead("HKCU\Software\Microsoft\Notepad\lfFaceName")  ' 굴림
Return = WshShell.RegRead("HKCU\Software\Winamp\") ' C:\Program Files\Winamp
Return = WshShell.RegRead("HKCU\Software\WinRAR\") ' 기본값 없어서 에러 발생.

- strRegName : key or value-name

 

' strRegName의 루트키 약자
    HKEY_CURRENT_USER         :   HKCU
    HKEY_LOCAL_MACHINE       :   HKLM
    HKEY_CLASSES_ROOT         :   HKCR
    HKEY_USERS                       :   HKEY_USERS
    HKEY_CURRENT_CONFIG      :   HKEY_CURRENT_CONFIG

 

' 레지스트 경로의 마지막에 백슬래시 \ 가 있으면 키, 없으면 값의 이름을 가리킨다.

' 키나 값이 존재하지 않을 경우, 값이 바이너리값인 경우 -> 에러 발생.

' 키의 default value 가 존재하지 않을 경우 -> 에러 발생.
' REG_SZ 값은 String 을 읽어온다.
' REG_DWORD 값은 dword 값이 아닌 실제 정수값을 읽어온다.
' REG_BINARY 값은 읽지 못한다. (에러 발생)
' REG_EXPAND_SZ 값은 String 문자열 그대로 읽어온다.
=========================================================

WshShell.RegWrite strRegName, anyValue [, strType]

- strRegName : key or value-name

' 키    추가 : strRegName에 \ 를 붙여준다.
' 이름 추가 : strRegName에 \ 를 붙이지 않음.
' strRegName에 \ 붙이고 Value 가 공백(zero-length string) 이면 빈 새 키가 생성된다

- anyValue
' value에 Dword 값 입력시에는 dowrd값이 아닌 실제 정수(십진수)로 입력해야 함.
' value에 쌍따옴표 포함된 String 입력시 다시 쌍따옴표로 감싸주거나 Chr(34) 를 이용한다.
' value에 경로문자 \가 포함된 String 입력시 \ 는 \\ 로 바꿔 입력할 필요가 없다.
' value에 환경변수 포함된 String 입력하면 변환된 값이 아닌 환경변수 문자열 그대로 입력된다.

- strType (Registry Data Type)
REG_SZ               : 문자열 (String)
REG_DWORD        : 정수 (Integer)
REG_EXPAND_SZ : 문자열 ( %comspec% 등과 같은 환경 변수를 포함하는 경우)
REG_BINARY        : 이진 문자열

' 값의 형식 지정하지 않으면 REG_SZ 로 인식
' REG_MULTI_SZ 값 입력은 지원되지 않음.

 

WshShell.RegWrite "HKCU\Software\AAA\", ""   ' 빈 새키 생성

WshShell.RegWrite "HKLM\...\ValName", 1000, "REG_DWORD" ' dword:000003e8 입력시

WshShell.RegWrite "HKCU\..", """%ProgramFiles%\..""", "REG_EXPAND_SZ"

 

Dim WshEnv : Set WshEnv = WshShell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
WshShell.RegWrite "HKCU\..", Chr(34) & ProgramDir & "\some.txt" & Chr(34), "REG_SZ"

' REG_EXPAND_SZ타입은 %~%를 문자열 그대로 입력.

' 맞는 값으로 변환시켜 입력하려면 Environment 등을 이용하여 값을 얻어 입력해야 함.

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

WshShell.RegDelete strRegName

- strName : key or value-name

WshShell.RegDelete "HKCU\MyNewKey\"                ' 키    삭제 : 맨 뒤에 \ 를 붙여준다
WshShell.RegDelete "HKCU\MyNewKey\MyValue"    ' 이름 삭제 : 맨 뒤에 \ 를 붙이지 않음


 예문)

Dim WshShell : WshSet Shell = createobject ("wscript.shell")
Const vbYes = 6
Dim p : p = WshShell.Popup ("would you like to GO ON?:  ", 5, "go on qestion", vbYesNo+vbQuestion)

If p = vbYes Then
    MsgBox "ok"
Else
    set p = nothing
    Wscript.Quit
End If

 

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
Dim BtnCode : BtnCode = WshShell.Popup("Do you feel alright ?", 7, "Answer This Question:", 4 + 32)

Select Case BtnCode
   case 6   WScript.Echo "Glad to hear you feel alright."
   case 7   WScript.Echo "Hope you're feeling better soon."
   case -1  WScript.Echo "Is there anybody out there?"
End Select

 

Dim MyVar : MyVar = MsgBox ("안녕하십니까?", 65, "메시지 상자 예제")

' vbOKCancel(1) + vbInformation(64) = 65

 

Dim strReturn : strReturn = InputBox ("What is the sum of 1 + 5 * 9 / 3 ?  ", "The Math Game")
Dim TrimReturn : TrimReturn = Trim(strReturn)
If Len(TrimReturn) = 0 Then
    MsgBox "Sorry. You must enter a number to play this game."
    WScript.Quit
End If

If IsNumeric(TrimReturn) <> True Then
    MsgBox "Sorry. You must enter a number to play this game."
    WScript.Quit
End If

 

// JScript
var WshShell = WScript.CreateObject("WScript.Shell");
var BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32);
switch(BtnCode) {
   case 6:
      WScript.Echo("Glad to hear you feel alright.");
      break;
   case 7:
      WScript.Echo("Hope you're feeling better soon.");
      break;
   case -1:
      WScript.Echo("Is there anybody out there?");
      break;
}

 

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

Return = WshShell.RegRead(strRegName)

Return = WshShell.RegRead("HKCU\Software\Microsoft\Notepad\lfFaceName")  ' 굴림
Return = WshShell.RegRead("HKCU\Software\Winamp\") ' C:\Program Files\Winamp
Return = WshShell.RegRead("HKCU\Software\WinRAR\") ' 기본값 없어서 에러 발생.

- strRegName : key or value-name

 

' strRegName의 루트키 약자
    HKEY_CURRENT_USER         :   HKCU
    HKEY_LOCAL_MACHINE       :   HKLM
    HKEY_CLASSES_ROOT         :   HKCR
    HKEY_USERS                       :   HKEY_USERS
    HKEY_CURRENT_CONFIG      :   HKEY_CURRENT_CONFIG

 

' 레지스트 경로의 마지막에 백슬래시 \ 가 있으면 키, 없으면 값의 이름을 가리킨다.

' 키나 값이 존재하지 않을 경우, 값이 바이너리값인 경우 -> 에러 발생.

' 키의 default value 가 존재하지 않을 경우 -> 에러 발생.
' REG_SZ 값은 String 을 읽어온다.
' REG_DWORD 값은 dword 값이 아닌 실제 정수값을 읽어온다.
' REG_BINARY 값은 읽지 못한다. (에러 발생)
' REG_EXPAND_SZ 값은 String 문자열 그대로 읽어온다.
=========================================================

WshShell.RegWrite strRegName, anyValue [, strType]

- strRegName : key or value-name

' 키    추가 : strRegName에 \ 를 붙여준다.
' 이름 추가 : strRegName에 \ 를 붙이지 않음.
' strRegName에 \ 붙이고 Value 가 공백(zero-length string) 이면 빈 새 키가 생성된다

- anyValue
' value에 Dword 값 입력시에는 dowrd값이 아닌 실제 정수(십진수)로 입력해야 함.
' value에 쌍따옴표 포함된 String 입력시 다시 쌍따옴표로 감싸주거나 Chr(34) 를 이용한다.
' value에 경로문자 \가 포함된 String 입력시 \ 는 \\ 로 바꿔 입력할 필요가 없다.
' value에 환경변수 포함된 String 입력하면 변환된 값이 아닌 환경변수 문자열 그대로 입력된다.

- strType (Registry Data Type)
REG_SZ               : 문자열 (String)
REG_DWORD        : 정수 (Integer)
REG_EXPAND_SZ : 문자열 ( %comspec% 등과 같은 환경 변수를 포함하는 경우)
REG_BINARY        : 이진 문자열

' 값의 형식 지정하지 않으면 REG_SZ 로 인식
' REG_MULTI_SZ 값 입력은 지원되지 않음.

 

WshShell.RegWrite "HKCU\Software\AAA\", ""   ' 빈 새키 생성

WshShell.RegWrite "HKLM\...\ValName", 1000, "REG_DWORD" ' dword:000003e8 입력시

WshShell.RegWrite "HKCU\..", """%ProgramFiles%\..""", "REG_EXPAND_SZ"

 

Dim WshEnv : Set WshEnv = WshShell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
WshShell.RegWrite "HKCU\..", Chr(34) & ProgramDir & "\some.txt" & Chr(34), "REG_SZ"

' REG_EXPAND_SZ타입은 %~%를 문자열 그대로 입력.

' 맞는 값으로 변환시켜 입력하려면 Environment 등을 이용하여 값을 얻어 입력해야 함.

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

WshShell.RegDelete strRegName

- strName : key or value-name

WshShell.RegDelete "HKCU\MyNewKey\"                ' 키    삭제 : 맨 뒤에 \ 를 붙여준다
WshShell.RegDelete "HKCU\MyNewKey\MyValue"    ' 이름 삭제 : 맨 뒤에 \ 를 붙이지 않음

 

' 레지스트리 읽어서 .reg 파일로 저장
Set WshShell = CreateObject("WScript.Shell")
sKey = "HKEY_CURRENT_USER\Software\Microsoft\Notepad"

fName = "c:\TEMP\FirstPage.reg"
sCmd = "regedit /e/a " & Chr(34) & fName & Chr(34) & " " & Chr(34) & sKey & Chr(34)
WshShell.Run "%comspec% /c " & sCmd, 0, True

Set WshShell = Nothing
'================================================================
' 레지스트리 파일 읽어서 Program Files 경로 변경 후 병합하기

Option Explicit

'On Error Resume Next
'Err.Clear

 

Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
Dim ProgramDir : ProgramDir = Shell.Environment("Process").Item("ProgramFiles")

 

Const FindLong = "C:\\Program Files"
Const FindShort = "C:\\PROGRA~1"

 

Dim ProgArray, ProgLong, ProgShort
ProgArray = Split (ProgramDir, "\")
ProgLong = ProgArray(1)
ProgShort = ProgArray(1)

 

If Len(ProgLong) > 8 Then
    ProgShort = Left(ProgLong, 6) & "~1"    ' PROGRA~1
End If

 

Dim RepLong : RepLong = ProgArray(0) & "\\" & ProgLong
Dim RepShort : RepShort = ProgArray(0) & "\\" & ProgShort
' 레지파일의 경로 구분자는 \가 아닌 \\

 

Dim RegFile : RegFile = "install.reg"
Dim ts, strLine, newLine
Dim newReg : newReg = ""

 

If FSO.FileExists(RegFile) Then
    Set ts = FSO.OpenTextFile(RegFile, 1)  ' 1 => ForReading
    Do Until ts.AtEndOfStream
        strLine = ts.ReadLine
        newLine = Replace(strLine, FindLong, RepLong, 1, -1, 1)
        newLine = Replace(newLine, FindShort, RepShort, 1, -1, 1)
        newReg = newReg & newLine & vbCrLf
    Loop
    ts.Close

    Dim fTmp : fTmp = FSO.GetAbsolutePathName(FSO.GetTempName)
    FSO.CreateTextFile(fTmp)
    Dim getTmp : Set getTmp = FSO.GetFile(fTmp)
    Dim tsTmp : Set tsTmp = getTmp.OpenAsTextStream(2, True)  ' Const ForWriting = 2
    tsTmp.Write(newReg): tsTmp.Close
    Shell.Run "%COMSPEC% /C regedit /s " & Chr(34) & fTmp & Chr(34), 0, True
    FSO.DeleteFile fTmp, True
End If


Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

'================================================================

' 프로그램 설치되었는지 여부 검사하기

Set WshShell = CreateObject("WScript.Shell")
If WshShell.RegRead("HKCR\.BMP\\") = "ACDC_BMP" Then
   WScript.Echo "ACDSee installed."
Else
   WScript.Echo "You can install ACDSee."
End If
         
Set WshShell = Nothing

 

 

- [Method] SendKeys

Dim WshShell : Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys string[, wait]

string   : 필수. 입력된 문자식을 보냅니다.
Wait   : 선택. 부울 값은 대기 모드로 지정합니다.
  False (기본값)이면 키가 입력이 되면 컨트롤은 바로 프로시저에 반환됩니다.
  True 이면 프로시저에게 컨트롤이 반환되기 전에 반드시 키가 입력되어야 합니다.

--------------------------------------------------------------------------

 

* 문자 입력 : 그 문자 자체를 표시.
    예) ABC   => "ABC"

 

* 기호 문자 입력 : 중괄호({})로 묶어준다.
    예) 덧셈 기호를 입력   =>  {+}

    더하기 기호   plus sign           +
    삽입 기호      caret                 ^
    퍼센트 기호   percent sign      %
    생략 기호      and tilde            ~
    괄호                                    ( )

 

 cf, 대괄호([ ]) :  대괄호는 그냥 입력이 가능하지만, 다른 응용프로그램에서 특수하게

                        인식될수 있으므로 중괄호로 묶어준다.
                        [  =>  {{}         ] => {}}

 

* 특수 키 입력
키                               코드
백스페이스                   {BACKSPACE}, {BS} 또는 {BKSP}
Break                          {BREAK}
Caps Lock                   {CAPSLOCK}
Del 또는 Delete             {DELETE} 또는 {DEL}
아래쪽 화살표               {DOWN}
End                             {END}
Enter                           {ENTER} 또는 ~
Esc                             {ESC}
Help                            {HELP}
Home                          {HOME}
Ins 또는 Insert              {INSERT} 또는 {INS}
왼쪽 화살표                  {LEFT}
Num Lock                    {NUMLOCK}
Page Down                 {PGDN}
Page Up                     {PGUP}
Print Screen                {PRTSC}
오른쪽 화살표              {RIGHT}
Scroll Lock                 {SCROLLLOCK}
Tab                            {TAB}
위쪽 화살표                 {UP}
F1      {F1}
F2      {F2}
F3      {F3}
F4      {F4}
F5      {F5}
F6      {F6}
F7      {F7}
F8      {F8}
F9      {F9}
F10    {F10}
F11    {F11}
F12    {F12}
F13    {F13}
F14    {F14}
F15    {F15}
F16    {F16}


* Shift,Ctrl,Alt 와 일반 키를 동시에 누를 경우 : 아래 문자를 입력할 키 앞에 붙여준다.

     Shift    +
     Ctrl     ^
     Alt      %

 조합키 누른채 다른 여러 키를 입력해야 한다면 여러 키들을 괄호로 묶어준다.
     Shift + ( E + C...)        =>      "+(ec)"
     (Shift +  E)  + C          =>      "+ec"

     Alt + F4                     =>      "%{F4}"

* 키 반복 입력 : 반복되는 키를 지정할 때는 {keystroke number}의 형식으로 나타낸다.

  (키와 숫자 사이에 반드시 공백 필요)
  
    왼쪽 화살표키를 42회 입력    =>   {LEFT 42}
    H를 10 번 입력                    =>   {h 10}

    Ctrl+X 를 10번 입력하는 식으로 특수키와 일반키의 조합을 여러번 입력하는건 안된다.

        alt + ctrl + del  => Shell.Sendkeys("%^{DEL}") x
                                 Shell.Sendkeys("%^+{DEL}") o

 

* 참고 *
Microsoft Windows 내에서 실행되지 않는 응용 프로그램에 SendKeys를 사용하여 키를

입력할 수 없다.
Sendkeys는 또한 PRINT SCREEN key {PRTSC} 를 다른 응용 프로그램에 보낼 수 없다.

 

 

 

-  [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)

 

- object : WshShell object.
- strCommand : String value indicating the command line you want to run.
- intWindowStyle : Optional. Integer value indicating the appearance of the program's window.

 

* intWindowStyle :
0    Hides the window and activates another window.
1    Activates and displays a window.

     If the window is minimized or maximized, the system restores it to its original size and position.
     An application should specify this flag when displaying the window for the first time.
2   Activates the window and displays it as a minimized window.
3   Activates the window and displays it as a maximized window.
4   Displays a window in its most recent size and position.

     The active window remains active.
5   Activates the window and displays it in its current size and position.
6   Minimizes the specified window and activates the next top-level window in the Z order.
7   Displays the window as a minimized window. The active window remains active.
8   Displays the window in its current state. The active window remains active.
9   Activates and displays the window.

    If the window is minimized or maximized, the system restores it to its original size and position.
     An application should specify this flag when restoring a minimized window.
10  Sets the show-state based on the state of the program that started the application.


- bWaitOnReturn : Optional. (true / false)

Boolean value indicating whether the script should wait for the program to finish executing
before continuing to the next statement in your script.
If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program.
If set to false (the default), the Run method returns immediately after starting the program,
automatically returning 0 (not to be interpreted as an error code).

- intError : Error code ( integer ).

-----------------------------------------------------------------------------------

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

 

 

 

-  [Method] Sign, SignFile, Verify, VerifyFile

Sign
   Signs a script stored in a string.

SignFile
   Signs a script using a digital signature.

 

Verify
   Verifies a digital signature retrieved as a string.

VerifyFile
   Verifies the digital signature encapsulated in a script.

 

 

-  [Method] CreateObject, GetObject

CreateObject
   Creates an object specified by the strProgID parameter.

 

CreateScript
   Creates a WshRemote object (an object that represents an instance of a script

   running in a remote process).

 

CreateShortcut
   Creates an object reference to a shortcut or URLshortcut.

 

 

ConnectObject
   Connects an object's event sources to functions with a given prefix.

 

DisconnectObject
   Disconnects a previously connected object from Windows Script Host.

 

 

GetObject
   Retrieves an Automation object from a file or an object specified by the strProgID parameter.

 

 

 [Method] MapNetworkDrive

 

MapNetworkDrive
   Maps the share point specified by strRemoteName to the local resource name strLocalName.

 

 

EnumNetworkDrives
   Returns the current network drive mappings.

EnumPrinterConnections
   Returns the current network printer mappings.

 

 

RemoveNetworkDrive
   Removes the current resource connection denoted by strName.

 

RemovePrinterConnection
   Removes the current resource connection denoted by strName.

 

 

 

AddPrinterConnection
   Adds a DOS-style printer connection to your computer.

 

AddWindowsPrinterConnection
   Adds a Windows-style printer connection to your computer.

SetDefaultPrinter
   Sets the default printer to the remote printer specified.

 

 

 

 

-  [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%"));


예문)

 

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

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

' C:
SystemDrive = WshShell.ExpandEnvironmentStrings("%SystemDrive%")

' C:\WINDOWS
SystemRoot = WshShell.ExpandEnvironmentStrings("%SystemRoot%")

' C:\WINDOWS
WinDir = WshShell.ExpandEnvironmentStrings("%WinDir%")

' C:\WINDOWS\system32\cmd.exe
comspec = WshShell.ExpandEnvironmentStrings("%comspec%")

' C:\Documents and Settings\USER
UserProfile = WshShell.ExpandEnvironmentStrings("%UserProfile%")

' C:\Documents and Settings\All Users
AllUsersProfile = WshShell.ExpandEnvironmentStrings("%AllUsersProfile%")

' C:\Documents and Settings\USER\Application Data
AppData = WshShell.ExpandEnvironmentStrings("%AppData%")

' C:\Program Files
ProgramFiles = WshShell.ExpandEnvironmentStrings("%ProgramFiles%")

' C:\DOCUME~1\USER\LOCALS~1\TEMP
Temp = WshShell.ExpandEnvironmentStrings("%Temp%")
Tmp = WshShell.ExpandEnvironmentStrings("%Tmp%")


WScript.Echo Tmp

 

* MakeList.vbs *

' [1] 인자로 폴더경로만 입력받는 경우
Option Explicit

Dim Shell : Set Shell = Wscript.CreateObject("Wscript.Shell")
Dim FSO : Set FSO = WScript.CreateObject("Scripting.FileSystemObject")

Const OutName = "FileList.txt"   ' 목록을 작성하여 저장할 txt 파일 - 고정

If Wscript.Arguments.Count = 1 Then
    Dim ArgPath : ArgPath = WScript.Arguments(0)
    Dim OutFile : OutFile = FSO.BuildPath(ArgPath, OutName) ' BuildPath - 완전한 경로 생성
    If FSO.FolderExists(ArgPath) Then ' 경로는 쌍따옴표 Chr(34) 로 감싸준다.
        Shell.Run "%comspec% /c Dir " & Chr(34) & ArgPath & Chr(34) _
        & " > " & Chr(34) & OutFile & Chr(34) & " /b /n /-d"
    Else  ' cmd.exe dir <directory> /b /n /-d    (파일명만 목록으로 출력됨)
        WScript.Echo "** Source directory not found ** " & ArgPath
    End If
Else
    WScript.Echo "사용 형식 : MakeList.vbs <source path>"
    WScript.Echo "사용 예문 : MakeList.vbs c:\temp"
End If

Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

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

' [2] 인자로 폴더경로와 결과저장 파일을 받는 경우

Option Explicit

Dim Shell : Set Shell = Wscript.CreateObject("Wscript.Shell")
Dim FSO : Set FSO = WScript.CreateObject("Scripting.FileSystemObject")

If Wscript.Arguments.Count = 2 Then  ' 인자가 두 개 여야 함
    Dim ArgPath : ArgPath = WScript.Arguments(0)
    Dim OutFile : OutFile = WScript.Arguments(1)
    If FSO.FolderExists(ArgPath) Then
If Left(OutFile, InstrRev(OutFile, "\")) = "" or FSO.FolderExists(Left(OutFile, InstrRev(OutFile, "\"))) Then
    Shell.Run "%comspec% /c Dir " & Chr(34) & ArgPath & Chr(34) & " > " _

    & Chr(34) & OutFile & Chr(34) & " /b /n /-d"
Else
    WScript.Echo "** Destination path not found ** " & Left(OutFile, InstrRev(OutFile, "\"))
End If
    Else
        WScript.Echo "** Source directory not found ** " & ArgPath
    End If
Else
    WScript.Echo "사용 형식 : MakeList.vbs <source path> <destination file>"
    WScript.Echo "사용 예문 : MakeList.vbs c:\temp c:\test.txt"
End If

Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

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

예문)

 

 

-폴더내 파일목록 작성

 

* MakeList.inf *

; MakeList.vbs 복사  +  레지스트리 등록

; .vbs 파일과 .inf 파일이 동일한 폴더내에 있어야 함.

[Version]
Signature="$Windows NT$"

 

[DefaultInstall]
CopyFiles = Add_File
AddReg    = List_Reg

 

[DestinationDirs]
Add_File   = 11    ;  system32

 

[Add_File]
MakeList.vbs,,,0x00000010    ; 0x00000010  =>  COPYFLG_NO_OVERWRITE

 

[List_Reg]
HKCR,"Directory\shell\VB.List\",,,"Print File &List"
HKCR,"Directory\shell\VB.List\command\",,,"wscript.exe ""%11%\MakeList.vbs"" ""%1"""

;   [HKEY_CLASSES_ROOT\Directory\shell\VB.List]
;   @="Print File &List"
;   [HKEY_CLASSES_ROOT\Directory\shell\VB.List\command]
;   @="\"C:\\WINDOWS\\system32\\MakeList.vbs\" \"%1\""

 

 

<프로그램 설치를 위한 세가지 작업>

1. 폴더 복사 (폴더  -> C:\Program Files\폴더)

2. 바로가기 생성 (시작메뉴, 바탕화면)

2. 레지스트리 병합 (regedit /s install.reg)

 

 

 

- Install, Uninstall

* Install.vbs *

 

Option Explicit

On Error Resume Next
Err.Clear

Dim Shell : Set Shell = WScript.CreateObject ("WScript.Shell")
Dim FSO : Set FSO = WScript.CreateObject ("Scripting.FileSystemObject")

 

Const ProgID = "flyExplorer"  ' flyExplorer 1.63 을 설치하는 경우

' 프로그램명은 바뀌지 않으므로 상수 Const 로 선언해버린다.

 

Dim LinkDir : LinkDir = Shell.SpecialFolders("Programs") & "\" & ProgID
Dim ExeDir : ExeDir = Shell.Environment("Process").Item("ProgramFiles") & "\" & ProgID
Dim DeskDir : DeskDir = Shell.SpecialFolders("Desktop")
Dim UnKey : UnKey = "HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\" & ProgID & "\"

' ProgID => 복사할 폴더명, 프로그램 폴더에 생성될 폴더명, 시작메뉴 폴더명


If Not FSO.FolderExists(LinkDir) Then FSO.CreateFolder LinkDir End If
FSO.CopyFolder ProgID, ExeDir, True

 

' 바로가기 파일은 .lnk 확장자를 가진다.

Dim ExeLink : Set ExeLink = Shell.CreateShortcut(LinkDir & "\flyExplorer.lnk")
'ExeLink.HotKey = "CTRL + SHIFT + F"
ExeLink.TargetPath = ExeDir & "\flyExplorer.exe"
ExeLink.WorkingDirectory = ExeDir
ExeLink.Save
Set ExeLink = Nothing

 

Dim DeskLink : Set DeskLink = Shell.CreateShortcut(DeskDir & "\flyExplorer.lnk")
DeskLink.TargetPath = ExeDir & "\flyExplorer.exe"
DeskLink.Save
Set DeskLink = Nothing

 

Dim UnLink : Set UnLink = Shell.CreateShortcut(LinkDir & "\Uninstall flyExplorer.lnk")
UnLink.TargetPath = ExeDir & "\uninstall.vbs"
UnLink.Save
Set UnLink = Nothing

 

Shell.Run "regedit /s install.reg"

 

Shell.RegWrite UnKey & "DisplayName", "flyExplorer v1.63"
Shell.RegWrite UnKey & "UninstallString", "wscript """ & ExeDir & "\uninstall.vbs"""

' 제어판 삭제 메뉴를 위한 레지스트리 정보(DisplayName, UninstallString  -> 필수 요소)

' uninstall.vbs 실행을 위해 c:windows\system32\wscript.exe 를 이용한다.

 

Set Shell = Nothing
Set FSO = Nothing

WScript.Quit
============================================================================

* Uninstall.vbs *

 

Option Explicit

' On Error Resume Next
' Err.Clear

' 실제 적용시에는 위 두줄 앞의 ' 가 없어야 에러나도 계속 진행하게 됨.

 

Dim Shell : Set Shell = WScript.CreateObject ("WScript.Shell")
Dim FSO : Set FSO = WScript.CreateObject ("Scripting.FileSystemObject")

 

Const ProgID = "flyExplorer"  ' flyExplorer 1.63

 

Dim LinkDir : LinkDir = Shell.SpecialFolders("Programs") & "\" & ProgID
Dim ExeDir : ExeDir = Shell.Environment("Process").Item("ProgramFiles") & "\" & ProgID
Dim DeskLink : DeskLink = Shell.SpecialFolders("Desktop") & "\flyExplorer.lnk"

Dim UnKey : UnKey = "HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\" & ProgID & "\"

 

If MsgBox ("flyExplorer 1.63을 제거하시겠습니까?   ", 33, "Uninstall - " & ProgID) = 1 Then
    Call DelReg("HKCU\Software\flyExplorer\")
    Call DelReg(UnKey)
    Call DelFile(DeskLink)
    Call DelFolder(LinkDir)
    Call DelFolder(ExeDir)
End If

 

Sub DelReg(key)
    On Error Resume Next ' 키나 값이름이 존재하지 않으면 에러 -> 이걸 출력 못하게 함.
    Shell.RegDelete key
End Sub
Sub DelFolder(fold)
    If FSO.FolderExists(fold) Then
        FSO.DeleteFolder fold, True
    End If
End Sub
Sub DelFile(file)
    If FSO.FileExists(file) Then
        FSO.DeleteFile file, True
    End If
End Sub

 

Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

----------------------------

<WinRAR-SFX 설명문>

Path=flyExplorer

SavePath
Setup=install.vbs
TempMode
Silent=1
Overwrite=1

 

 

 

- 폴더(파일)명 일괄변경

* ReNamer.vbs *

 

입력 1. 대상 폴더 경로의 마지막에 \ 가 있으면 파일명 변경, 없으면 폴더명 변경.

입력 2. 찾을 단어, 바꿀 단어 를 입력받는다.

       - 쉼표로 구분

       - 바꿀 단어는 공백이 올 수 있다( = 특정 문자 제거)

       - 찾을 단어가 숫자 0 이라면 맨 앞 접두어 삽입으로 간주한다.

 

Option Explicit

'On Error Resume Next
'Err.Clear

Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = WScript.CreateObject("Scripting.FileSystemObject")

Dim TargetPath, fileMode

 

TargetPath = InputBox ("대상 폴더의 절대경로를 입력해 주세요." _
    & vbCrLf & "마지막에 \가 있으면 파일명 변경, " _
    & vbCrLf & "없으면 폴더명 변경입니다.  "  _
    & vbCrLf & vbCrLf & "예) C:\Temp  또는   C:\Temp\", "Parent Path")

' InputBox 는 Popup 과는 달리 오브젝트(WshShell)없이 단독으로 사용 가능.

 

Call CheckNull(TargetPath)
TargetPath = Trim(TargetPath)

 

' 기본은 폴더명 변경 , 경로 마지막에 \ 가 있으면 파일명 변경

' \ 가 붙은 경우, 대상 폴더의 경로를 얻기 위해 마지막 \ 는 제거해 줘야 한다.
fileMode = False
If Right(TargetPath, 1) = "\" Then
    TargetPath = Left(TargetPath, Len(TargetPath)-1) ' 마지막 \ 제거
    fileMode = True
End If

Call CheckRoot(TargetPath)

If fileMode = True Then
    Call RepFiles
Else
    Call RepFolders
End If

 

'[함수화]*******************************
Sub CheckRoot(s)
    If Trim(s) = "" Then ' 경로 입력 안했거나 취소버튼 누른 경우
        WScript.Quit
    ElseIf Len(s) <= 3 Then ' C  C:  C:\  등의 경우
        Shell.Popup "루터 디렉토리는 대상 폴더가 될 수 없습니다.  ", 3, "Path Error", vbOkOnly
        WScript.Quit
    ElseIf Not FSO.FolderExists(s) Then
        Shell.Popup "경로가 존재하지 않습니다.  ", 3, "Path Error", vbOkOnly
        WScript.Quit
    End If
End Sub
Sub CheckNull(s)
    If Trim(s) = "" Then
        Shell.Popup " 입력값 없음  ", 1, "Input Empty", vbOkOnly
        WScript.Quit
    End If
End Sub
Sub CheckRest(s)
    If InStr(1, s, ",", 1) <= 0 Then ' s 에서 쉼표가 위치한 곳(순서가 <= 0 는 말은 없다는 뜻)
        Shell.Popup "찾을 단어와 바꿀 단어를 쉼표로 구분하여 입력해 주세요.  ", 3, "Input Error", vbOkOnly
        WScript.Quit
    End If
End Sub

 

'[파일명 변경]***************************
Sub RepFiles
    Dim inputStr : inputStr = InputBox ("* 파일명 변경 *" & vbCrLf _
    & "찾을 단어와 바꿀 단어를 쉼표로 구분하여 입력해 주세요." & vbCrLf & vbCrLf _
    & "교체) target words, new words" & vbCrLf _
    & "삭제) target words," & vbCrLf _
    & "접두어 삽입) 0, insert words", "파일명 변경")
    Call CheckNull(inputStr)
    Call CheckRest(inputStr)
    Dim StrArray : StrArray = Split(inputStr, ",", -1, 1)  ' 쉼표로 구분(배열을 생성)
    Dim FindStr : FindStr = LTrim( StrArray(0) )  ' 단어 왼쪽 공백만 없앤다.
    Call CheckNull(FindStr)
    Dim RepStr : RepStr = LTrim( StrArray(1) ) ' 바꿀 단어는 Null Check 안함.

    Dim objFold : Set objFold = FSO.GetFolder(TargetPath)
    Dim fcoll : Set fcoll = objFold.Files

    ' Folder.files 와 Folder.subfolders는 콜렉션 객체를 생성한다.
    Dim f1, oName, nName, oPath, nPath
    For Each f1 in fcoll
        oName = f1.name  ' 하위 파일의 이름
        If IsNumeric(FindStr) Then ' 찾을 문자가 숫자 0 이면 접두어 삽입 모드
            nName = RepStr & oName
        Else
            nName = Replace(oName, FindStr, RepStr, 1, -1, 1)
        End If
        oPath = TargetPath & "\" & oName
        nPath = TargetPath & "\" & nName
        If Not FSO.FileExists(nPath) Then ' 같은 이름 있으면 변경 안함
            FSO.MoveFile oPath, nPath
        End If
    Next
    Set objFold = Nothing
    Set fcoll = Nothing
End Sub

 

'[폴더명 변경]***************************
Sub RepFolders

    Dim inputStr : inputStr = InputBox ("* 폴더명 변경 *" & vbCrLf _
    & "찾을 단어와 바꿀 단어를 쉼표로 구분하여 입력해 주세요." & vbCrLf & vbCrLf _
    & "교체) target words, new words" & vbCrLf _
    & "삭제) target words," & vbCrLf _
    & "접두어 삽입) 0, insert words", "폴더명 변경")
    Call CheckNull(inputStr)
    Call CheckRest(inputStr)

    Dim StrArray : StrArray = Split(inputStr, ",", -1, 1)  ' 쉼표로 구분(배열을 생성)
    Dim FindStr : FindStr = LTrim( StrArray(0) ) ' 단어 왼쪽 공백만 없앤다.
    Call CheckNull(FindStr)
    Dim RepStr : RepStr = LTrim( StrArray(1) )

    Dim objFold : Set objFold = FSO.GetFolder(TargetPath)
    Dim dcoll : Set dcoll = objFold.SubFolders
    Dim d1, oName, nName, oPath, nPath
    For Each d1 in dcoll
        oName = d1.name  ' 하위 폴더의 이름
        If IsNumeric(FindStr) Then
            nName = RepStr & oName
        Else
            nName = Replace(oName, FindStr, RepStr, 1, -1, 1)
        End If
        oPath = TargetPath & "\" & oName
        nPath = TargetPath & "\" & nName
        If Not FSO.FolderExists(nPath) Then ' 같은 이름 있으면 변경 안함
            FSO.MoveFolder oPath, nPath
        End If
    Next
    Set objFold = Nothing
    Set dcoll = Nothing
End Sub


Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

 

WSH - ex) 코덱박사 슈퍼코덱팩 자동설치

* AutoInstall.vbs *

 

Option Explicit

On Error Resume Next 

Err.Clear


Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%COMSPEC%")

Dim ExeFile : ExeFile = "Super_20060524.exe"   ' 파일명 바꾸면 설치 에러남

 

If MsgBox ("코덱박사 슈퍼 코덱팩 v20060524 을 설치하시겠습니까?   " , 36, "Setup - SuperCodec") = 6 Then
 Shell.Run COMSPEC & " /c " & ExeFile & " & Exit", 0

 'cmd창 숨기고 설치창 활성화.  뒤에 ,true 붙이면 안됨
 Wscript.Sleep 3000
 Shell.AppActivate "코덱박사 슈퍼 코덱팩 v20060524"  '활성창 타이틀
 Wscript.Sleep 800
 Shell.SendKeys "~", True ' 엔터키

 Wscript.Sleep 1000
 Shell.SendKeys "~", True
 Wscript.Sleep 1000
 Shell.SendKeys "{TAB}", True
 Wscript.Sleep 500
 Shell.SendKeys "{right}", True
 Wscript.Sleep 500
 Shell.SendKeys "~", True

 Wscript.Sleep 1000
 Shell.SendKeys "~", True
 Wscript.Sleep 1000
 Shell.SendKeys "~", True
 Wscript.Sleep 1000

 Shell.SendKeys "{TAB}", True
 Wscript.Sleep 500
 Shell.SendKeys "{END}", True '맨아래칸 이동은 {down} 쓸 필요없이 바로 {END} 로..
 Wscript.Sleep 1000
 Shell.SendKeys " ", True ' PCClear는 설치요소에서 제거 ( " " -> 스페이스키)
 Wscript.Sleep 1000

 Shell.SendKeys "{TAB}", True
 Wscript.Sleep 500
 Shell.SendKeys "{right}", True
 Wscript.Sleep 500
 Shell.SendKeys "~", True

 Wscript.Sleep 1000
 Shell.SendKeys "~", True

 Wscript.Sleep 1000
 Shell.SendKeys "~", True

 Wscript.Sleep 3000

 Shell.SendKeys "~", True ' GomPlayer 발견 - 최적화할까요?  => yes

 ' GomPlayer , KMPlayer 등 미디어재생 소프트웨어를 먼저 설치해야 한다.
 Wscript.Sleep 3500
 Shell.SendKeys "~", True ' nomal
 Wscript.Sleep 1000
 Shell.SendKeys "~", True ' 2 channel
 Wscript.Sleep 1000
 Shell.SendKeys "~", True ' 환경설정

 ' Call DelStartup() ' 한글Windows에서는 하면 안됨...


Else
    Shell.Popup "코덱박사 슈퍼 코덱팩 v20060524 설치가 취소되었습니다.   ", 3, "Cancle", 48
    WScript.Quit
End if

 

' 영문Windows에는 "시작프로그램"이라는 폴더가 없다. ( Start Menu 가 있다 )

Sub DelStartup()

    Dim KorStartMenu : KorStartMenu = Shell.SpecialFolders("Programs") & "\시작프로그램"
    If FSO.FolderExists(KorStartMenu) Then
        FSO.DeleteFolder KorStartMenu
    End If
End Sub

 

Set Shell = Nothing
Set FSO = Nothing

WScript.Quit

 

 

 

-
WSH - ex) 곰플레이어 1.9 자동설치

 

* AutoInstall.vbs *

 

Option Explicit

On Error Resume Next
Err.Clear

 

Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")

Dim WshEnv : Set WshEnv = Shell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")

' COMSPEC 지정할 필요없이 바로 Shell.Run "%comspec%~ 해도 됨..

 

Const ExeFile = "GOM.EXE"  '고정된 이름은 변수가 아닌 상수로 지정해도 무방..

 

If MsgBox ("곰플레이어 1.9를 설치하시겠습니까?  ", 36, "Setup - GomPlayer") = 6 Then

    Shell.Run COMSPEC & " /c " & ExeFile & " & Exit", 0

    ' 0 => cmd창 숨기고 설치창 활성화.   뒤에 ,true 붙이면 안됨
    Wscript.Sleep 3000
    Shell.AppActivate "곰플레이어 설치"
    Wscript.Sleep 800
    Shell.SendKeys "~", True ' next [엔터]
    Wscript.Sleep 800
    Shell.SendKeys "~", True ' 동의
    Wscript.Sleep 1000

    Shell.SendKeys "{TAB}", True ' 구성요소 (모든 동영상 확장자 등록 체크)
    Wscript.Sleep 500
    Shell.SendKeys "{DOWN}", True
    Wscript.Sleep 500
    Shell.SendKeys "{DOWN}", True
    Wscript.Sleep 500
    Shell.SendKeys "{DOWN}", True
    Wscript.Sleep 500
    Shell.SendKeys " ", True
    Wscript.Sleep 800
  
    Shell.SendKeys "~", True
    Wscript.Sleep 1000
    Shell.SendKeys "{DEL}", True  ' delete 키
    Wscript.Sleep 800
    Shell.SendKeys ProgramDir & "\GomPlayer", True ' 설치경로 변경( c:\prog~\Gomplayer )
    Wscript.Sleep 800
    Shell.SendKeys "~", True
    Wscript.Sleep 6500
    Shell.SendKeys "{TAB}", True
    Wscript.Sleep 800
    Shell.SendKeys "~" , True

Else
    Shell.Popup "곰플레이어 설치가 취소되었습니다.   ", 3, "Cancle", 48
    WScript.Quit
End if

 

' 바로가기 폴더(아이팝) 지우고 GomPlayer 새로 생성
Dim Programs : Programs = Shell.SpecialFolders("Programs") ' or AllUsersPrograms
Dim OldShortDir : OldShortDir = Programs & "\아이팝 (www.ipop.co.kr)"
Dim NewShortDir : NewShortDir = Programs & "\GomPlayer"

FSO.DeleteFolder OldShortDir
FSO.CreateFolder NewShortDir

 

Dim ExeLink : Set ExeLink = Shell.CreateShortcut(NewShortDir & "\곰플레이어.lnk")
ExeLink.HotKey = "CTRL+SHIFT+G"
ExeLink.TargetPath = ProgramDir & "\GomPlayer\Gom.exe"
ExeLink.WorkingDirectory = ProgramDir & "\GomPlayer"
ExeLink.Save

Set ExeLink = Nothing

 

Dim ManLink : Set ManLink = Shell.CreateShortcut(NewShortDir & "\곰매니저.lnk")
ManLink.TargetPath = ProgramDir & "\GomPlayer\GomMgr.exe"
ManLink.WorkingDirectory = ProgramDir & "\GomPlayer"
ManLink.Save

Set ManLink = Nothing

 

Dim UnLink : Set UnLink = Shell.CreateShortcut(NewShortDir & "\곰플레이어 제거.lnk")
UnLink.TargetPath = ProgramDir & "\GomPlayer\Uninstall.exe"
UnLink.Save

Set UnLink = Nothing

 

' _ad_temp_.ini 파일이 을 읽기전용으로 속성 변경.

' 최초 실행 전이라면 _ad_temp_.ini 파일이 아직 생성되지 않았음.

' _ad_temp_.ini 파일이 없는 상태라면 Gom.exe 를 실행시키야 환경설정창이 뜬다.
Dim iniFile : iniFile = ProgramDir & "\GomPlayer\_ad_temp_.ini"

Dim WizFile
If FSO.FileExists(iniFile) Then
    WizFile = "GomWiz.exe"
Else
    WizFile = "Gom.exe"
End If
 
Dim WizExec : Set WizExec = Shell.Exec(ProgramDir & "\GomPlayer\" & WizFile)
Wscript.Sleep 1000
Shell.AppActivate "언어 선택"
Shell.SendKeys "~" , True
Wscript.Sleep 800
Shell.AppActivate "곰플레이어 환경 설정 길잡이"
Wscript.Sleep 800
Shell.SendKeys "~" , True  ' 일반 모드
Wscript.Sleep 800
Shell.SendKeys "~" , True  ' 자체 코덱, 2채널 스피커
Wscript.Sleep 800
Shell.SendKeys "~", True

Wscript.Sleep 800
Shell.SendKeys "~" , True
Wscript.Sleep 800
Shell.SendKeys " " , True  ' 곰플레이어 실행 - 체크해제
Wscript.Sleep 800
Shell.SendKeys "~" , True
Wscript.Sleep 1500
Shell.SendKeys "{ESC}" , True  ' 곰플레이어 끄기

 

' WizExec 작업이 완전히 끝나야 다음으로 넘어간다.

' Run 과 Exec 의 차이 : Exec는 결과가 오브젝트로 생성되므로 이걸 다시 이용할 수 있다.

Do While WizExec.Status <> 1
 WScript.Sleep 100
Loop

 

Call SetReadOnly(iniFile)

 

Shell.Run  "regedit /s config.reg"

'Shell.Popup  "곰플레이어 1.9 설치가 완료되었습니다.   ", 3


'_ad_temp_.ini 파일을 읽기전용으로..
Sub SetReadOnly(f)
   Dim f1 : Set f1 = FSO.CreateTextFile(f, true) ' 덮어쓰면서 생성
   Dim f2 : Set f2 = FSO.GetFile(f1)
   f2.Attributes = 1
   Set f1 = Nothing
   Set f2 = Nothing
End Sub


Set Shell = Nothing
Set FSO = Nothing
Set WshEnv = Nothing
Set WizExec = Nothing

WScript.Quit

------------------------------

<config.reg>

Windows Registry Editor Version 5.00

; 옵션설정 - 업데이트 자동확인(x), 비슷한 파일명 열기(x), 재생시에만 맨위

[HKEY_CURRENT_USER\Software\GRETECH\GomPlayer\OPTION]
"bActiveMsg"=dword:00000000
"bCheckUpdate"=dword:00000000
"bNotifyUpdate"=dword:00000000
"bNotifyMinorUpdate"=dword:00000000
"bNotifySimilarFile"=dword:00000000
"idMenuLang"=dword:00000412
"idAudioLang"=dword:00000412
"idSubtitlesLang"=dword:00000412
"nOnTopMode"=dword:00000002

 

cf, 곰플레이어 2.0 버전 이상은 자동설치시 픽~ (Kill Processor).f

이 글은 스프링노트에서 작성되었습니다.

.

'Computer > ASP' 카테고리의 다른 글

zip,unzip 컴포넌트  (0) 2012.08.10
xmlhttp 를 통한 데이터 교환  (0) 2012.08.10
asp 용 UTF8 컨버터  (0) 2012.08.10
효율적인 페이징 기법  (0) 2011.11.29
ASP 에서 UTF-8 처리  (0) 2011.11.29