Friday, 21 October 2011

A VBScript Example to Copy Files to User Temp Folder

Below is an example of VBScript codes to copy files from current folder to '[User Profile]\Local Settings\Temp' folder then execute an executable file under the folder:
Set objShell = WScript.CreateObject("WScript.Shell")
currentFolder = objShell.CurrentDirectory

Dim filesys
Set filesys = CreateObject("Scripting.FileSystemObject")

Set appShell = CreateObject("Shell.Application")


'Set the destination folder to be checked/created

'these commented codes would use a folder under 'Program Files'
'Const PROGRAM_FILES = &H26&
'Set objFolder = appShell.Namespace(PROGRAM_FILES)
'Set objFolderItem = objFolder.Self
'Wscript.Echo objFolderItem.Path    'testing
'destinationFolderPath = objFolderItem.Path & "\MyApp\Install" 

'using '[User Profile]\Local Settings\Temp' folder, this value can be retrieved by using
'   filesys.GetSpecialFolder(2)     or      objShell.ExpandEnvironmentStrings("%temp%")
'testing - Wscript.Echo filesys.GetSpecialFolder(2)   ' or objShell.ExpandEnvironmentStrings("%temp%")
destinationFolderPath = objShell.ExpandEnvironmentStrings("%temp%") & "\MyApp.TMP"


'Check if folder exists
Dim newfolder
If Not filesys.FolderExists(destinationFolderPath) Then
    'if not then create one
    Set newfolder = filesys.CreateFolder(destinationFolderPath)
Else
    'clear all existing files under the destination folder
    filesys.DeleteFile(destinationFolderPath & "\*"), true  ' true - delete read only files
End If


'Copy all files under current folder to the destination folder
filesys.CopyFile currentFolder & "\*.*", destinationFolderPath & "\", true  ' true - overwrite existing


'Run installer
objShell.Run ("""" & destinationFolderPath & "\setup.exe" & """")
'objShell.Run ("""" & destinationFolderPath & "\setup.exe" & """"), 0, true     ' 0 - Hides the window and activates another window.
                                                                                ' true - the script should wait for the program to finish executing before continuing to the next statement


'Finalise
set appShell = Nothing
set filesys = Nothing
set objShell = Nothing
Wscript.Quit

No comments: