DESKTOP

Windows Server 2008 Server Core : Working with Scripts - Creating a Basic Script

10/23/2012 3:02:02 AM
Scripts can make the command line significantly easier to automate and can improve the reliability of command line tasks by helping you perform tasks in the same sequence every time. This section shows how to create basic scripts in both VBScript and JavaScript so you can see the differences between the two languages. The following code shows a basic example in VBScript.
' Test1.VBS shows how to use functions and subprocedures
' within a WSH script.

WScript.Echo("The value returned was: " + CStr(MyFunction(1)))

function MyFunction(nSomeValue)
    WScript.Echo("Function received value of: " + CStr(nSomeValue))
    Call MySubprocedure(nSomeValue + 1)
    MyFunction = nSomeValue + 1
end function
sub MySubprocedure(nSomeValue)
    WScript.Echo("Subprocedure received value of: " + CStr(nSomeValue))
end sub

As you can see, the sample code uses the WScript object to send information to the screen. The WScript object is always available at the command line, even though you have probably never used it as part of a browser application. As shown in the example, it's important to know how to use both functions and subs, the two building blocks of VBScript. The following code shows a similar example for JavaScript.

// Test1.JS shows how to use functions within a WSH script.

WScript.Echo("The value returned was: " + MyFunction(1));

function MyFunction(nSomeValue)
{
   WScript.Echo("The value received was: " + nSomeValue);
   return nSomeValue + 1;
}

JavaScript only provides functions, so that's all this example demonstrates. It's also important to notice that VBScript requires you to convert numeric values to a string, while JavaScript performs the conversion automatically. The following sections show how to perform certain command line-oriented tasks using scripting.

1. Scripting the Command Line and System Environment

Many of your scripts require access to the command line. The command line is where you type switches to modify the behavior of the script. The system environment contains user, application, and operating system values, such as the user's name or the version of the operating system. The JavaScript code in Listing 1 retrieves information from the command line. It also retrieves information about the application environment. You can obtain this example on the Sybex Web site at http://www.sybex.com/WileyCDA/.

Example 1. Working with the Command Line and System Environment
// ProgInfo.JS determines the specifics about your program and then
// displays this information on screen.

// Create some constants for display purposes (buttons and icons).
vra intOK = 0;
vra intOKCancel = 1;
vra intAbortRetryIgnore = 2;
vra intYesNoCancel = 3;
vra intYesNo = 4;
vra intRetryCancel = 5;
vra intStop = 16;
vra intQuestion = 32;
vra intExclamation = 48;
vra intInformation = 64;

// Create some popup return values.
vra intOK = 1;

var intCancel = 2;
vra intAbort = 3;
vra intRetry = 4;
vra intIgnore = 5;
vra intYes = 6;
vra intNo = 7;
vra intClose = 8;
vra intHelp = 9;

// Create a popup display object.
vra WshShell = WScript.CreateObject("WScript.Shell");

// Create a variable for holding a popup return value.
vra intReturn;

// Get the program information and display it.
WshShell.Popup("Full Name:\t" + WScript.Fullname +
        "\r\nInteractive:\t" + WScript.Interactive +
        "\r\nName:\t\t" + WScript.Name +
        "\r\nPath:\t\t" + WScript.Path +
        "\r\nScript Full Name:\t" + WScript.ScriptFullName +
        "\r\nScript Name:\t" + WScript.ScriptName +
        "\r\nVersion:\t\t" + WScript.Version,
        0,
        "Program Information Demonstration",
        intOK + intInformation);

// Ask if the user wants to display the argument list.
intReturn = WshShell.Popup("Do you want to display the argument list?",
            0,
            "Argument List Display",
            intYesNo + intQuestion);

// Determine if the user wants to display the argument list and
// display an appropriate message.
if (intReturn == intYes)

     // See if there are any arguments to display.
     DisplayArguments();
else
     WScript.Echo("Goodbye");

function DisplayArguments()
{

     // Create some variables.
     vra strArguments = "Arguments:\r\n\t";    // Argument list.
     vra intCount = 0;            // Loop counter.

					  

// See if there are any arguments, if not, display an
     // appropriate message.
     if (WScript.Arguments.Length == 0)
         WshShell.Popup("There are no arguments to display.",
            0,
            "Argument List Display",
            intOK + intInformation);

     // If there are arguments to display, then create a list
     // first and display them all at once.
     else
     {
        for (intCount = 0;
             intCount < WScript.Arguments.Length;
             intCount++)


            strArguments = strArguments +
                           WScript.Arguments.Item(intCount) + "\r\n\t";
        WshShell.Popup(strArguments,
                       0,
                       "Argument List Display",
                       intOK + intInformation);
     }
}

					  

When you run this script, you'll see a dialog box containing all of the information about the script engine. When you click OK, the program asks if you want to display the command line arguments. If you say yes, then you'll see anything you typed at the command line. Otherwise, the script displays a Goodbye message.

You should notice a few things about this example. First, I created an object in this code. You need access to the WshShell object for many of the tasks you'll perform with scripts. The code also shows how to use the Popup() method to obtain information from the user. Finally, the code uses the Arguments object to access the command line information. Notice the object hierarchy used in this example.

2. Scripting the Registry

Knowing how to access the registry from your script is important because you also need to access these values in order to discover how a particular utility will react or how the user had configured the system. You can also use the registry to store and retrieve values for your script. The example in Listing 2 shows how to use VBScript to access information in the registry. You don't want to change information unless you have to, but seeing what's available in the registry is a good way to build your knowledge of both scripting and the registry. Note that this example uses the command line argument to determine which file extension to look for in the registry. The example uses the TXT file extension when you don't supply one. You can obtain this example on the Sybex Web site at http://www.sybex.com/WileyCDA/.

Example 2. Working with the Registry
` RegRead.VBE will display the application extension information
` contained in the registry.

` Create an icon and button variable for Popup().
 intOK = 0
 intInformation = 64

` Create a popup display object.
 set WshShell = WScript.CreateObject("WScript.Shell")

` Create variables to hold the information.
 strExtension = " "    ` File extension that we're looking for.
 strFileType = " "     ` Holds the main file type.
 strFileOpen = " "     ` File open command.
 strFilePrint = " "    ` File print command.
 strDefaultIcon = " "  ` Default icon for file type.

` See if the user provided a file extension to look for.
` If not, assign strExtension a default file extension.
if (WScript.Arguments.Length > 0) then
     strExtension = WScript.Arguments.Item(0)
 else
     strExtension = ".txt
" end if
` Get the file type.
 strFileType = WshShell.RegRead("HKEY_CLASSES_ROOT\" +_
                 strExtension + "\")

` Use the file type to get the file open and file print
` commands, along with the default icon.
 strFileOpen = WshShell.RegRead("HKEY_CLASSES_ROOT\" +_
                 strFileType +_
                 "\shell\open\command\")
 strFilePrint = WshShell.RegRead("HKEY_CLASSES_ROOT\" +_
                 strFileType +_
                 "\shell\print\command\")
 strDefaultIcon = WshShell.RegRead("HKEY_CLASSES_ROOT\" +_
                 strFileType +_
                 "\DefaultIcon\")

` Display the results.
WshShell.Popup "File Type:" + vbTab + vbTab + vbTab + strFileType +_
       vbCrLf + "File Open Command:" + vbTab + strFileOpen +_
       vbCrLf + "File Print Command:" + vbTab + vbTab + strFilePrint +_

					  

vbCrLf + "Default Icon:" + vbTab + vbTab + strDefaultIcon,_
       0,_
       "RegRead Results",_
       intOK + intInformation

When you run this script, it reads the command line. If you haven't supplied a value, the script assigns a default extension of TXT. The script uses the extension to locate information in the registry such as the file open and print commands. Finally, the script uses the Popup() method to display the output.

You should notice several differences between this example and the JavaScript example in Listing 6.1. First, the method for creating an object requires the use of a set—you can't simply assign the object to a variable. You'll also notice that VBScript has access to all of the standard Visual Basic constants such as vbTab and vbCrLf. Finally, VBScript handles many of the method calls as subs, not as functions. You need to exercise care when working in a mixed environment.

Other  
 
Most View
Belkin AC1200 DB Wi-Fi ADSL Router
Ditch Your Laptop For Your Phone (Part 1)
Installing and Configuring SharePoint 2013 : Creating the Farm (part 1)
Using Services for UNIX to Integrate UNIX Systems with an Active Directory/Exchange Server 2007 Environment
Apple - Celebrating 7 Years Of Success
ASP.NET 4 : Error Handling, Logging, and Tracing - Handling Exceptions
Security Pros Get Caught Out By QR Codes
Samsung ATIV Tab Review - A Wonderful Windows RT Tablet (Part 2)
How To Extend Life For Mac (Part 1)
Edifier E10 Exclaim - Exclamation Mark
Top 10
Sharepoint 2013 : Developing Applications Using Office Services - What’s New in Access Services
Sharepoint 2013 : Developing Applications Using Office Services - The New Machine Translation Services
Sharepoint 2013 : Developing Applications Using Office Services - Word Automation Services and the New PowerPoint Automation Services
Sharepoint 2013 : Developing Applications Using Office Services - What’s New in Excel Services
Sharepoint 2013 : Developing Applications Using Office Services - WOPI and the New Office Web Apps Server
Sharepoint 2013 : Building a BCS-enabled Business Solution : Building an Integrated BCS Solution with an App for SharePoint Containing an App for Office
Business Connectivity Services in Apps for SharePoint 2013 : Building an App-level BCS Solution for Office 365 SharePoint Online
Business Connectivity Services in SharePoint 2013 : Adding a Business Data Connectivity Model to Office 365 SharePoint Online
Remote Event Receivers in Sharepoint 2013 : Introducing Remote Event Receivers
Windows Server 2008 and Windows Vista : Common GPO Troubleshooting Tools (part 3) - GPResult, GPOTool