DESKTOP

Windows Vista : Scripting and Automation - Wacky Script Ideas

9/26/2012 1:53:06 AM
The point of scripting is that instead of using a canned application to perform a certain task, you can easily and quickly throw together a script that does exactly what you need. That said, you may need some inspiration to get you cooking.

1. Quick and Dirty Backup Tool

The script in Example 1 starts by prompting you for the name of a folder to back up and checks whether it exists. If not, it gives you an opportunity to either type another folder name or exit. Once you've entered a valid folder name, the script creates a backup of the entire folder on a removable drive (set with the TargetDrive variable), such as a USB memory key or flash card.

Example 1. Quick and dirty backup tool
On Error Resume Next
TargetDrive = "K"
Accepted = False
Do Until Accepted
  MyFolder = InputBox("Please enter the name of the folder_
       you want to back up.")
  If Not FolderExists(MyFolder) Then
    Answer = MsgBox("The folder you typed doesn't exist._
         Try again?", 36, "")
    If Answer = 7 Then WScript.Quit
  Else
    Accepted = True
  End If
Loop

Answer = MsgBox("Please get drive " & TargetDrive & ": ready.", 33, "")
If FolderSize(MyFolder) > DriveFreeSpace(TargetDrive) Then
  MsgBox "The folder you specified won't fit on this drive.", 16
  WScript.Quit
End If

If FolderCreate(TargetDrive & ":\Backup\") = False Then
  MsgBox "There was a problem writing to drive " & TargetDrive & ":.", 16
  WScript.Quit
End If

Call FolderCopy(MyFolder, TargetDrive & ":\Backup\")

If Right(MyFolder, 1) <> "\" Then MyFolder = MyFolder & "\"
Call WriteToFile(MyFolder & "backuplog.txt",_
             "Last backed up: " & Now)

					  

This script uses several MsgBox prompts and, if used unaltered, will probably irritate just about anybody. (Hint: think about who will be using the scripts you write when you decide how much error checking and prompting is appropriate.) However, it also shows part of the power of interactive scripting: a little intelligent planning and error trapping can keep your scripts running smoothly, interrupting you only when necessary. For instance, note the use of the FolderExists function at the beginning of the script; rather than risking encountering an error, the script checks for a potential problem (a missing file) and then takes the necessary steps to resolve it. If the folder doesn't exist and the user doesn't want to try again, the user can exit; always give your users a choice to get out if they want.

Because the script implements some degree of error checking, the line On Error Resume Next appears at the beginning of the script. This statement instructs WSH to simply ignore any errors it finds. This doesn't automatically resolve any errors; it just eliminates the error message that would otherwise appear in the event of an error, allowing the script to skip problems and continue uninterrupted. This way, you're only bothered with the errors that concern you.

This example also uses the Do...Loop loop structure  at the beginning of the script. The code inside such a loop is repeated until a specific condition is met; in this case, the loop will repeat until the Accepted variable has a value of True (notice that it's set to False at the beginning of the script). The If...Then structures ensure that the Accepted variable is only set to True if the folder actually exists.

The second part of the script compares the total size of the folder and all its contents with the amount of free space on the target drive. You could expand the script, so that if the diskette is not sufficient to store the folder, the user is given the opportunity to insert another diskette and try again. You'd need to use a similar Do...Loop, as described earlier.

Once the script has gone through all of the tests (eliminating the possibility of most errors), the FolderCopy subroutine copies the folder to the floppy. Finally, the WriteToFile subroutine records in a logfile that the folder was backed up. Note also the preceding line that adds a backslash ( \) to the end of the MyFolder variable; this way, you can pass a valid filename (the folder name followed by a backslash and then the filename) to the WriteToFile subroutine.


2. Internet Fishtank

Nothing exemplifies the power of the Internet more than an Internet-enabled fishtank. This, essentially, is a web page with a dynamic picture of the contents of a fishtank. There are several ways to do this, but the following shows that it can be done with nothing more than a script, a webcam and a common FTP account.


These listings assume that the camera program and all images it creates are stored in the folder C:\camera. Start with the script shown in Example 2.

Example 2. Internet fishtank script
On Error Resume Next
ImageFile = "c:\camera\fish.jpg"
Call FileDelete(ImageFile)
Call RunProgram("c:\camera\camera.exe " & ImageFile, True)
If Not FileExists(ImageFile) Then WScript.Quit
Call RunProgram ("ftp -n -s:c:\camera\ftpscript.txtmyhost.com", False)

The script starts by suppressing all error messages, as described in the previous example. The subsequent lines use the snapshot utility that comes with nearly all cheap webcams to snap a still photo and save it to a .jpg image file. Note also the line that deletes the old file before the photo is taken, and the line thereafter that checks for the existence of the file before proceeding (in case something went wrong); this way, the script never sends the same photo twice. The inclusion of True in the RunProgram line instructs the script to wait for the camera.exe program to complete before the script continues, necessary for a script like this to work. You could alternatively incorporate a Do...Loop loop instead of the simple If statement to repeatedly check for the file over the course of several seconds.

The last line then runs the FTP utility that comes with Windows Vista to transfer the JPG file to a web server (available for free from nearly all Internet service providers). Normally, FTP is an interactive program, requiring that the user type commands into the console, but the -n and -s options shown here eliminate the need for user interaction. Replace myhost.com with the name of the server containing your web account. Example 3 shows the FTP script used by the WSH script in Example 9-3; type it into a plain-text file and save it as ftpscript.txt.

Example 3. FTP script for use with Internet-fishtank script
usermylogin
pass mypassword
bin
cd public_html
put c:\camera\fish.jpg
bye

The FTP script, like a batch file, is simply a text file containing the commands (in order) that you'd otherwise type manually into the FTP console window. Naturally, you'll want to replace the specifics, like mylogin and mypassword, with your own login and password, respectively, and public_html with the directory containing your public HTML files. Note that all commands must be typed lowercase. Type FTP -? at the Command Prompt for more command-line parameters.

Next, you'll want to set up a scheduled task to repeatedly run the script; the interval (five seconds, five minutes, etc.) depends on your needs and the capabilities of your system. Lastly, if you haven't already done it, create a web page that references the fish.jpg photo; just visit the page to view a current picture of your fishtank, from anywhere in the world. You can even include JavaScript code in the page to automatically reload itself and update the picture after a certain delay.

3. Quick SendTo Shortcut Creator

Explorer's SendTo menu contains a list of programs and shortcuts to which any selected file can be sent. The idea is to list programs that could be used with any type of file, such as an email program or file viewer, without having to specifically set up file associations for each supported file type. The following script (Example 4) allows you to right-click on any application executable (.exe file), folder, or drive and create a shortcut in the SendTo folder on the spot.

Example 4. SendTo shortcut creator
SendToFolder = GetSpecialFolder("SendTo")

Call Shortcut("SendToFolder\Notepad.lnk", CommandLine(1))

Whenever you can, you should try to make your scripts "smart." If you wanted to be lazy, all you'd need is the second line of this script, which creates a shortcut based on the command-line parameter . However, the first line uses the GetSpecialFolder function to obtain the location of the SendTo folder from the Registry, which is handy if there's more than one user account (each with its own SendTo folder), if you intend to use this script on more than one computer, or if you don't want to have to modify the script when Microsoft changes the location of the SendTo folder in the next version of Windows (which it did for Vista, dontcha know).

Once the script has been written, you'll need to associate it with all file types. 

4. Rename Files with Search and Replace

Although Explorer lets you rename more than one file at a time, it's not terribly flexible or intuitive. The Command Prompt provides a decent multiple-file renaming tool, but it's not always convenient. Example 5 shows a script that will rename all the files in a given folder based on rules you choose.

Example 5. File-renaming script
On Error Resume Next
FolderName = InputBox("Enter the name of the folder:")
If Not FolderExists(FolderName) Then WScript.Quit
SearchText = InputBox("Type the text to look for:")
ReplaceText = InputBox("Type the text with which to replace" _
                                              & SearchText & ":")
If SearchText = "" or ReplaceText = "" Then WScript.Quit

Set FileObject = CreateObject("Scripting.FileSystemObject")
Set FolderObject = FileObject.GetFolder(FolderName)
Set FilesObject = FolderObject.Files

FileCount = 0
For Each Filename in FilesObject
  If InStr(Filename.Name,SearchText) Then
    Filename.Name = Replace(Filename.Name,SearchText,ReplaceText)
    FileCount = FileCount + 1
  End If
Next

If FileCount > 0 Then
  MsgBox FileCount & " files were renamed."
Else
  MsgBox "No filenames containing " & SearchText & " were found."
End If

					  

The first section of code is responsible for asking for input, including the folder name, the text to look for, and the text with which to replace it. The next three lines set the appropriate objects (for further documentation on these objects, check http://msdn.microsoft.com/scripting).

The For...Next structure that follows does the real work: this particular example uses a special form of the loop intended to cycle through all the elements of an object collection. In this case, the collection contains the filenames of all the files in the specified folder. The Replace function (built into VBScript) then does the search and replace for each individual filename. Lastly, the FileCount variable tallies the number of files renamed, the result of which is displayed in the final code section.

Now, it may take some experience to understand the extensive use of objects in this example, but for the time being, just typing it in will serve as a good example that can be used in other circumstances. 

Note that a far more powerful file-renaming utility, Power Rename (part of Creative Element Power Tools), is available for Windows Vista (download it from http://www.creativelement.com/powertools/).
Other  
  •  Windows 7 : Programming Drivers for the User Mode Driver Framework - Required Driver Functionality, UMDF Sample Drivers
  •  Windows 7 : Programming Drivers for the User Mode Driver Framework - Windows I/O Overview, Brief COM Information, UMDF Architecture
  •  Installing Windows Small Business Server 2011 (part 2) - Understanding the Installation Process
  •  Installing Windows Small Business Server 2011 (part 1) - Performing a Clean Windows SBS 2011 Installation
  •  Preparing Your Windows 8 PC : Connecting to Wireless Networks
  •  Preparing Your Windows 8 PC : Setting App Notifications - Changing Notifications
  •  Gainward Geforce GTX 690 4GB For The Most Dedicated Gamers
  •  Portable Drive Algato Thunderbolt SSD
  •  Laptop HD Pavillion DM1 - 3200SA - The Thinnest Ultraportables
  •  Samsung Series 5 550 Chromebook – A real “paperweight” ?
  •  
    Video
    Top 10
    New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
    SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
    The latest Audi TT : New angles for TT
    Era of million-dollar luxury cars
    Game Review : Hearthstone - Blackrock Mountain
    Game Review : Battlefield Hardline
    Google Chromecast
    Keyboards for Apple iPad Air 2 (part 3) - Logitech Ultrathin Keyboard Cover for iPad Air 2
    Keyboards for Apple iPad Air 2 (part 2) - Zagg Slim Book for iPad Air 2
    Keyboards for Apple iPad Air 2 (part 1) - Belkin Qode Ultimate Pro Keyboard Case for iPad Air 2
    REVIEW
    - First look: Apple Watch

    - 3 Tips for Maintaining Your Cell Phone Battery (part 1)

    - 3 Tips for Maintaining Your Cell Phone Battery (part 2)
    Popular Tags
    Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone