After the basics of variables, Selection and Iteration statements, let us do something useful in real life. We start with the first object FileSystemObject. This gives us access to the filesystem. An essential part of scripting. We may need to create files, modify content, look for their existence. The idea is to make you familiar with using objects as well.
Let us take an example
Set fs = CreateObject("Scripting.FileSystemObject") |
Save this script as fsdrives.vbs
Run it
C:\scripts>cscript fsdrives.vbs //nologo C:\scripts> |
I have three drives on my laptop. Your machine may have more or less. Let us understand the code.
Line 1 is creating an object of FileSystemObject type. Without this you cannot use what is in this object. An object is contains methods (functions) and variables. The variables may be simple variables or may be collections. Collections are more like an array, you can use a for loop to go through each of the items, and then access the properties of each.
fs is an instance of the FileSystemObject
fs.drives is referencing a property of the FileSystemObject
fs.drives returns a collection of drives.
To loop through it we need a for loop. dc is the drive collections we have used. You have a collections of drives. For each drive there are many properties. We are referencing one of the property called driveletter.
Let us make the above program more richer. We not only need the drive, but also want to know the capacity and free space.
' Main Code Starts here Set fs = CreateObject("Scripting.FileSystemObject") ' We have explored, volumename, filesystem, totalsize, freespace |
Copy and paste the code. Run it.
C:\scripts>cscript fsdrives.vbs //nologo Number of Drives 3 C:\scripts> |
That is the output I get. Your challenge would be to fine tune the code further so that the numbers are aligned below each other. On your machine you may see more or less drives and the numbers different.
No comments:
Post a Comment