Example Batch File to Identify a User and Run a VBScript File

Here is the syntax for writing a simple batch file that checks the user name of the account that is running the script, and then executes a VBScript file if the user name is positively matched. As part of the test, I’ll show how to execute the VBScript from the batch file while suppressing an intentional error message thrown in the VBScript file. 

Identifying and Filtering the Current Computer User

As you can see from the code example below, you can get the identity of the currently logged on user using the %USERNAME% environment variable.

To check if that user id is the expected one, you’ll need to write an IF…Else statement. Note that batch files don’t support Else If, so if you have several IF conditions, then you’ll need to nest them.

Also note that string equivalency comparisons can be done either using double equals signs == or EQU. You’ll need to add the /i option to your string comparison to make sure that the comparison is case-insensitive.

An interesting part of this IF condition is that you don’t need to put the user id in quotes… aka: you don’t need quotes around literal strings.

Executing the VBScript Silently

Ok, so now that we’ve correctly identified a user, we’ll want to execute a VBScript file. As part of this test, we want to run the VBScript file in non-windowed mode, and we want to suppress any messages thrown by the file. We can accomplish this using cscript to run the VBScript file, which will run it in non-windowed mode. Then to suppress any text or error messages generated in the VBScript file, we add the parameter //B, which executes the script silently.

To test the silent and non-windowed execution of the VBScript file, I’ve created a file called testscript.vbs. This file contains a single line (Err.Raise 5) that intentionally throws an error: Invalid Procedure Call or Argument

Finally, after a positive match of the user id and silent execution of the VBScript file, you may want to stop execution of any further code. You can exit your batch file code execution right away using the EXIT /B command.

Below I’m including example code for the batch file and the VBScript file that it calls.

The Batch File Code

@echo off
echo %USERNAME%
IF /i %USERNAME% EQU MyUserId (
echo "found"
cscript //B "testscript.vbs"
EXIT /B
) ELSE (
echo "user not found"
)
echo "script execution complete"

The VBScript (“testscript.vbs”)

Err.Raise 5

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s