Tuesday 10 January 2012

Batch File Automation Part-2

As discussed in the previous thread. A Batch file along with VB can used to automate a process.

Let us consider a requirement where you are suppose to place a file in a directory. The directory might have a file already with same name as the one being moved. This is very easy when we do it manually as the OS would through a error saying "file with same name already exists and do you want to replace it"  and we can easily click on yes and continue. But when we automate we should be able to move the file with out any discrepancies.

Let us see how such a automation can be done.

Steps
1. Create a Batch file that would create a New file by name "Move_Me.txt" at C:\Test
2. The batch file would then try to move the file to C:\Test\Moved using a VBS

Fig : Showing the files used in the example 
The details of the files

CreateFile.bat
This file has the following lines to


@Echo off
Echo "I will be Moved" > C:\Test\Move_Me.txt
Echo "File Move_Me.txt has been created. File would be moved now...."
pause
Start MoveFile.vbs


The above piece of code would first create a File Move_Me.txt with test as "I will be Moved".
Then the code would display message on the screen saying "File Move_Me.txt has been created. File would be moved now...." and pause would wait for user input.
Start command would kick start the MoveFile.vbs which would move the Move_Me.txt to the destination folder.

MoveFile.vbs
VB script is as below



FilePath = "C:\Test\"
Filename = "Move_Me.txt"
NewPath = "C:\Test\Moved\"
Set ScriptObj = CreateObject("Scripting.FileSystemObject")

If ScriptObj.FileExists(FilePath & Filename) Then
    If ScriptObj.FileExists(NewPath & Filename) Then
        ScriptObj.DeleteFile (NewPath & Filename)
    End If
ScriptObj.MoveFile (FilePath & Filename), (NewPath & Filename)
    End If
Set ScriptObj = Nothing

The code is hard coded with the values of file path and file name. Not a good programming practice. But for beginner this should be fine. How ever we will discuss on how parameters can be passed with a different example.

Try this out and let us discuss if any better way of doing this.

Stay tunned for upcoming topics.........

No comments:

Post a Comment