Share via


Simple Scripting Technique With VBScript and PowerShell

Although more time has passed since my last post than I had realized, I wanted to post something to the point but still useful for some.  One of the things that I have grown to enjoy over the years is scripting and automation.  Sometimes it can save you hours of work and thousands of dollars and yet sometimes it may have been quicker to perform the task manually.  In either event, I take opportunities as they come to automate tasks so I can save time or at the least, save it for a rainy day when I may need to do that same thing again.

 So today I am going to do something very basic and simple.  I am going to show some sample vbscript code that will read a specified directory and display out the names of all files inside of that directory.  This is the very simple beginner script, so it does not do things like recurse subdirectories or account for things like the directory you specify being missing.  Those are more complex and I will post some of those things in the future.

 So to start off, I have made the script to allow you to feed it the directory to search, rather than hard-coding it into the code.

 sFolder = Wscript.Arguments.Item(0)

Set objFolders = fso.GetFolder(sFolder)
Set objFiles = objFolders.Files

For Each File In objFiles
wscript.echo File
Next 

To run the above code successfully, I would run it in a command prompt with something like this:

c:>cscript script-name.vbs c:temp

In that example, the script would scan "c:temp" and report back the files it find in that directory.  Yes, running "dir c:temp" from any command prompt would accomplish similar results, but by doing it in vbscript it opens up all sorts of possibilites.  Once I identify each file, I could provide a lot more data about each file and I could then perform other actions on them as I needed.  Again, I will cover some of that later.

In contrast, to do a similar task in powershell, it would be:

 GCI c:temp

or

Get-ChildItem c:temp

 That code would do basically the same as a "dir" at a command prompt whereas the vbscript would ONLY list the files in the directory and not subdirectory.  To make the above powershell recurse all the subdirectories, simply add "-R" to the command.

I hope to be able to post far more useful and complex scripts as time allows.  I will also try to point out the differences between the scripting techniques, like vbscript or powershell, as I walk through them.