30
Mon, Dec
0 New Articles

Microsoft Computing: Windows Scripting, Part I

Microsoft
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

The Windows operating systems and Internet Explorer include support for reading and executing stored instructions. Yes, I know, computers do that a lot, usually through means of programs, but this angle is a bit different. Scripted instructions are stored in a file as command statements in ordinary text form, much as source code statements are kept. Instead of being compiled into an executable form ahead of time, though, script statements are interpreted on the fly and executed. This has the advantage that a given source statement will be properly converted to machine instructions for the target platform it's running on.

Interpreting commands is not new, really. The iSeries has always had the capability to interpret commands from a database reader. Similarly, PCs have always had the ability to run .bat files.

Scripted instructions can be used to meet a variety of requirements, most commonly to perform some sort of batch process or to act as a small program. Some common scripted languages are JavaScript, PHP, Perl, Python, Ruby, and Visual Basic Script (VBScript.) VBScript is of particular interest because, like VB, it's very popular and it's the de facto standard for Windows.

VBScript can be used in multiple environments but always requires the help of a runtime interpreter. The interpreter is a program that accepts the script statements as input and performs the corresponding processing. In Windows, the runtime support comes either integrated into Internet Explorer or as standalone Windows programs named CScript.exe (for console output) or WScript.exe (for windowed output). Normally, if the task at hand is a batch process, one of the standalone versions is used. If the task is interactive, where a user interface is needed, the screen framework is provided by Internet Explorer. If Internet Explorer is to be used, the VBScript statements have to be embedded in an HTML file.

Note that not just any browser will do. As a security feature, Firefox and Netscape support neither VBScript nor ActiveX technologies. They do, however, support plug-ins, so the support for VBScript can be added (which defeats the reason for avoiding IE in the first place).

Microsoft defines these script components and provides an introduction for each:

  • Visual Basic, Scripting Edition (VBScript)--This scripting language is available by default with Microsoft Windows. See VBScript Primer.
  • Windows Script Host (WSH)--A script host can be thought of as a command interpreter. The WSH is the Windows environment in which your scripts run, and it allows you to do some things you couldn't otherwise. See WSH Primer.
  • Windows Management Instrumentation (WMI)--The WMI is an object model that is designed to be used to manage the Windows operating systems scripting. For example, if you want to know how much disk space is available, you can enlist the services of the WMI object. See WMI Scripting Primer.
  • Active Directory Service Interfaces (ADSI)--This technology provides you with the resources to manage Active Directory and other directory services through scripting. See ADSI Scripting Primer.

VBScript Compared to VB

VBScript is based on Visual Basic for Applications, rather than straight VB, and it's an interpreted language, so a number of things are done differently than they would be in VB. These are among the most significant:

  • Since script code is not compiled, it is plainly visible to anyone who cares to look at it. Likewise, any script you access can become a coding example.
  • There is no Interactive Development Environment for VBScript. That is, you do not launch a programming environment like Visual Studio. Instead, you make scripts the old-fashioned way--with a text editor such as Notepad and trial and error. Similarly, there is no forms designer to help you create your forms because VBScript does not support forms on its own.
  • There is no debugger for VBScript. If you're going to write a lot of script, you may do well to look into one of the third-party script debuggers.
  • The code syntax set for VBScript varies from VB. Many keywords are omitted from VBScript. (You can see a listing at HTML Goodies.)
  • Since the statements are interpreted and executed one at a time as they're encountered, you can't use older flow control references like goto, gosub...return, line numbers, etc.
  • Only the multi-purpose variable type of Variant is supported in VBScript. Since there's only one type of variable, data conversion operators like Chr$ are not included. String conversion operations (like UCase$) are not allowed, but variant conversion (like UCase) is OK.
  • VBScript cannot access API routines contained in external libraries.

VBScript in a Batch Environment--A Shell Example

So what does VBScript look like? "Hello World" looks like this:


WScript.echo "Hello World"

That's it. When run, this one line of code will display a message box with a button. Wow, that was easy.

Here's a bit more code in an example that uses the WScript.Shell object to retrieve the current version of the operating system:

Dim strWork (A)
Dim strCommand

Set WShell = CreateObject("WScript.Shell") (B)
Set WEnv = WShell.Environment("PROCESS") (C)
strWork = WEnv("OS") (D)

If strWork = "Windows_NT" Then
    WScript.echo "OS is " & strWork (E)
    'OK – Call installation command string...
    strCommand=chr(34) & "D:setup.exe" & chr(34) (F)
    WShell.Run strCommand, 1, False (G)
Else
    WScript.echo "Not an NT operating system."
    'Can't install – quitting... 
End If

These lines of code would be stored in a text file with .vbs as the extension. The Windows script program (WScript.exe or CScript.exe) can then be called from a DOS prompt or the Start/Run... launcher to execute the instructions:

C:>wscript myScript.vbs

The script will produce a message box indicating the version of Windows (as shown in Figure 1) and then go on to call setup.exe if appropriate.

http://www.mcpressonline.com/articles/images/2002/Microsoft-VBScript1V300.jpg

Figure 1: A message box is displayed by the Windows Script Host.

Some points of note in the script code shown above:

  • At line A, variables of type Variant are defined. Other data types are not supported in VBScript.
  • At line B, an object reference to an instance of the WScript.Shell is created dynamically.
  • At C, a reference to the shell's environment variables is created.
  • At D, the variable strWork gets the name of the operating system from the environment variable "OS".
  • Finally, at E, the variable is examined and some output is displayed.
  • If the OS is Windows NT, a program named D:setup.exe is called to perform the install at F and G.

Code like this would be used in a "convenience" script to perform a routine task like installing software on several PCs. Note that the WScript shell object does most of the processing; VBScript just creates the shell and passes requests to it (D and G). The WScript program can do that for us because it is a Component Object Model (COM) object and has an exposed external interface that can be used to ask the program to do things. It's also registered with the Windows system registry. That's how the statement CreateObject("WScript.Shell") knows which real program name to run and where it can be found.

A Windows Management Instrumentation Example

More in-depth Windows management tasks are performed in script with the help of the WMI. The WMI is also a registered COM application, so its services can be availed from a VBScript. The Microsoft example below can tell if a particular application is running (the Windows disk defragmentation utility in this case).

strComputer = "."
Set objWMIService = GetObject("winmgmts:"" & strComputer & " ootcimv2") (H)
Set colProcesses = objWMIService.ExecQuery _ (I)
    ("Select * from Win32_Process Where Name = 'Dfrgntfs.exe'")

If colProcesses.Count = 0 Then (J)
    Wscript.Echo " Dfrgntfs.exe is not running."
Else
    Wscript.Echo " Dfrgntfs.exe is running."
End If

This example differs from the WScript example because the WMI interface is different:

  • At statement H, the keyword GetObject is used instead of CreateObject as in the first example. That's because the process is already running as part of Windows. The statement renders a reference to the WMI process.
  • At I, a collection object is created from querying the WMI object. The collection contains only the processes named Dfrgntfs.exe.
  • If the number of processes in the collection is zero (at J), Dfrgntfs.exe is not running; otherwise, it is.

As before, the script is run with C:>wscript myScript2.vbs.

When executed, the script in the second code example will display the status of the defragmenting program (Figure 2).

http://www.mcpressonline.com/articles/images/2002/Microsoft-VBScript1V301.jpg

Figure 2: The WMI object can tell if a process is running.

Again, this is an example of using VBScript as a convenience process to deal with a specific condition that might result in a conflict. Scripts of this nature can also help reduce error-prone repetitive tasks by consolidating steps and performing error checks along the way.

Next month, I'll take up the topic of running VBScript in its most common application--within a Web browser as an interactive application.

Chris Peters has 26 years of experience in the IBM midrange and PC platforms. Chris is president of Evergreen Interactive Systems, a software development firm and creators of the iSeries Report Downloader. Chris is the author of The OS/400 and Microsoft Office 2000 Integration Handbook, The AS/400 TCP/IP Handbook, AS/400 Client/Server Programming with Visual Basic, and Peer Networking on the AS/400 (MC Press). He is also a nationally recognized seminar instructor. Chris can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: