Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


February 1999

WSH Logon Scripts


RSS
Subscribe to Windows IT Pro | See More Task Automation Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here
Download the Code Here
Download the Code Here

Sample Logon Script Migration
Now that you understand some of the problems you must consider when you convert logon scripts to WSH, I'll rewrite a batch file logon script in VBScript. Listing 2 contains a simple logon script, logon.bat, that uses NT's NET USE command to map a network drive and uses the NET TIME command to synchronize the local workstation's time with the time on the domain the workstation logs on to. Listing 3 contains a WSH script, logon.vbs, that performs the same functions. At first glance, logon.vbs might appear more complex than logon.bat, but remember that VBScript represents a different programming paradigm than batch files. The primary use of batch files is to glue together command-line utilities; VBScript glues together objects. As you gain experience with VBScript, you'll probably find that the language makes difficult scripts easier to write, enhance, and maintain.

Logon.vbs begins with VBScript's Option Explicit directive to force variable declarations. Next, the script uses the On Error Resume Next statement to enable runtime error handling; the statement lets the script continue executing even when the script encounters an error. Without the On Error Resume Next statement, runtime errors in logon.vbs would result in cryptic messages to the user, after which the script would immediately abort. After the On Error Resume Next statement, Listing 3 declares the script's variables, initializes strDrive and strShare, and uses WScript's CreateObject method to create the script's wshNetwork and wshShell objects. Logon.vbs later uses the wshNetwork object to map a drive to a network share, and the script uses the wshShell object to access system environment variables and run the NET TIME command.

At callout A in Listing 3, the script sets the wshSysEnv variable to the Environment property that the wshShell object exposes. Setting a variable to a wshShell object's Environment property returns a wshEnvironment object that exposes environment variables of the type the script specifies; you can expose SYSTEM, USER, VOLATILE, or PROCESS environment variables. Logon.vbs specifies the SYSTEM environment variable source.

Next, the script uses wshSysEnv to test the OS environment variable. If the OS environment variable matches the string Windows_NT, logon.vbs enters the If block at callout B. If the OS environment variable doesn't match Windows_NT, logon.vbs executes the Else block that appears near the end of the script. The Else block echoes an appropriate message to the user, removes objects the script has created, and exits the script with a return value of 1. If the script is running under cscript.exe, the return value of 1 sets the command processor's ERRORLEVEL value to 1, and the script's wrapper batch file can use ERRORLEVEL to determine whether the script did not complete successfully.

At callout B, the script uses the wshNetwork object's MapNetworkDrive method to map a drive to a network share. However, before logon.vbs maps the drive, it must verify that the client machine hasn't already used the target drive letter to set up a persistent network connection. Logon.vbs performs this verification by obtaining and traversing a network drive collection. It begins by invoking the wshNetwork object's EnumNetworkDrives method, which returns a collection (which you can think of as an array) of current network drive mappings. The script then traverses the collection and compares the even elements with the value of the variable strDrive. (The script compares strDrive with only the network drive collection's even elements because the EnumNetworkDrives method returns the drive mappings as Drive=Share pairs; the drives are the even elements and the shares are the odd elements in the collection.) If strDrive matches any of the even elements in the network drive collection, logon.vbs uses the RemoveNetworkDrive method to remove the current mapping to the target drive. After the script removes the drive mapping or verifies that the system hasn't mapped the target drive letter to another share, it maps strDrive to the network share strShare.

Logon.vbs's last task is running the NET TIME command. The script uses the wshShell object's Run method for this purpose. Run accepts three arguments: the name of the command to run, an optional integer that you can use to specify a type of window for the command to open, and an optional Boolean flag that dictates whether the script waits for the command to complete before continuing. At C in Listing 3, logon.vbs uses the wshNetwork object's UserDomain property and VBScript's string concatenation operator (the ampersand character$#151;&) to specify the target time-synchronization domain. The zero value for the Run command's second argument tells Run not to create a new window, and the TRUE value for the third argument forces the script to wait for the NET TIME command to complete before continuing.

When NET TIME completes, logon.vbs captures the NET TIME command's return value in the variable nReturnCode and tests this value to determine whether the time change was successful. If nReturnCode doesn't equal zero, logon.vbs uses VBScript's MsgBox function to display an appropriate error message. Finally, before exiting, the script destroys the wshNetwork and wshShell objects.

More Logon Script Functionality
The functions this article covers represent the tip of the iceberg in terms of WSH's capabilities as an engine for logon scripts. WSH resembles a real programming language in that the product lets you add real data types to your scripts, implement real control flow, and write real subroutines; batch files don't offer this functionality. VBScript's FileSystemObject provides more robust access to the file system than batch files provide. And WSH provides access to multiple directory services via ADSI, access to databases via ActiveX Data Object (ADO), and send-mail capabilities via Collaboration Data Object (CDO).

Use one of WSH's easy-to-learn scripting languages and support for other Microsoft and third-party components to teach your logon scripts new tricks. Become comfortable with WSH and VBScript today to make sure you're prepared to work with the platform of the new millennium.

End of Article

   Previous  1  [2]  Next  


Reader Comments
I dont understand something please. If I type %OS% in the run box on a XP and 2000 machine it returns "Windows_NT" I am missing something intrinsic to this method. Wouldn't it never fail if XP and 2000?

Thx in advance ,

Tony August 28, 2003


XP and 2000 run the nt kernel so they are considered nt for an os...

Troy November 24, 2003


i want run exe file using client vbscript (how use wscript.shell?)
what i do to run exe file on client machin from server-site?
thank u for help me or not help me

fahd elhariry December 17, 2003


Where do I place the logon scripts on a Windows Server 2003 machine for each domain user?

Pedro April 22, 2004


Hello,
How can i create an exe file from an ASP file

Rajitha April 25, 2004


\windows\sysvol\sysvol\scripts\

Noel April 26, 2004


Hello everyone, can anyone tell me how to protect the scripts from evil users. As I understand those logon scripts have to be available for the client, but then if they want to misuse it, or delete it they also can, that is a no no. So I am wondering what I can do. Thanks

Nile May 01, 2004


yeah Niles, put them in your sysvol or netlogon, then only admins will have write permission

matt May 25, 2004


Is there a way to run a login script that will display date and time of last login; the workstation ID of last login; and number of unsuccessful login attempts since last successful? I have a regulation I need to meet and cannot find a good solution for this requirement.

Anita June 09, 2004


Has anyone created vb scripts and successfully deployed them in a Windows98 section enviornment. I am running 2000 server.

Bret June 18, 2004


 See More Comments  1   2 

You must be a registered user or online subscriber to comment on this article. Please log on before posting a comment. Are you a new visitor? Register now




Top Viewed ArticlesView all articles
Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

WinInfo Short Takes: Week of November 9, 2009

An often irreverent look at some of the week's other news, including some more Windows 7 sales momentum, some Sophos stupidity, Microsoft's cloud computing self-loathing, more whining from the browser makers, Zoho's "Fake Office," and much, much more ...

Understanding File-Size Limits on NTFS and FAT

A general confusion about files sizes on FAT seems to stem from FAT32's file-size limit of 4GB and partition-size limit of 2TB. ...


Task Automation Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Will Your Next Generation Server System Meet Your Infrastructure Optimization Needs?

Continuous Data Protection and Recovery for Microsoft Exchange

Related Events WinConnections and Microsoft® Exchange Connections

Deep Dive into Windows Server 2008 R2 presented by John Savill

Check out our list of Free Email Newsletters!

Task Automation eBooks Spam Fighting and Email Security for the 21st Century

A Guide to Windows Certification and Public Keys

Keeping Your Business Safe from Attack: Patch Management

Related Task Automation Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement