Creating logon scripts with KiXtart, part 3

In this third installment of our series of Daily Drill Downs on using KiXtart, Richard Charrington shows you how to write scripts that let you communicate with the user, map network drives, and other cool tricks.

In part 1 of my series of Daily Drill Downs on scripting with KiXtart, I provided background information on KiXtart and discussed common structures and commands. In part 2 , I covered loops, subroutine calls, and the GoTo command. I also showed how KiXtart can execute external commands and scripts, described the Select construct, and went into some detail on registry manipulation.

In this installment, I’ll examine manipulating the DOS window that KiXtart will run in, communicating with a user, mapping network drives, and reading and writing files.

Now you see me, now you don't
You may want to create a hidden script screen if you create a login script screen that doesn’t require user intervention. It might also be useful to have a hidden script screen to keep your users from being confused by all the dialog information from programs running in your script. The SetConsole function enables you to maximize, minimize, resize, and even hide the DOS window that KiXtart runs in. The syntax is
where mode is one of the following:
  • SHOW—Show window
  • HIDE—Hide window
  • FOREGROUND—Move window to foreground
  • ALWAYSONTOP—Bring window to top
  • MINIMIZE—Minimize window
  • MAXIMIZE—Maximize window

It's good to talk
In part 1, I showed you two ways you can display information to the user: using a question mark (?) and using MessageBox. With MessageBox, it’s also possible to get input from the user—the result of clicking one of up to three buttons. Let’s take a look at other means of communicating with your user.

Get reads a line of characters from the keyboard until the [Enter] key is pressed and then stores the result in a variable. Here are some examples:
? "Continue (y/n): "
get $key
until $key = "y" OR $key = "n"
? ? "Enter your name: "
gets $line
Mapping drives
Rather than relying on persistent connections to hold standard mappings, you can get the logon script to make a connection whenever the user logs on. This ensures that even if the user “unmaps” a drive, the drive will be mapped again when the user logs on.

KiXtart provides the Use command for mapping, unmapping, and listing network drives. As you can see, the syntax is very similar to the Windows Net Use command:
USE <* | "device" | "resource"> /DELETE [/PERSISTENT]
USE ["device"] <"resource"> [/USER:user] [/PASSWORD:password] [/PERSISTENT]
The command Use * /DELETE will delete all current connections except those to a NetLogon share and those to the drive or share from which KiXtart was started. If a resource name contains a space or non-alphanumeric characters (such as - or +), you must enclose the name in quotation marks. On Windows NT only, the /USER and /PASSWORD parameters enable overriding the security context of the current user.

Check the value of @ERROR to see if Use was successful. A value of 0 indicates success.

Here are some examples:
USE E: \\SERVER\PUBLIC /user:Me /password:mine
USE LPT1: \\SERVER\LASER /user:testDomain\USER1

USE H: @HOMESHR ; connect to user's home share
 CD @HOMEDIR ; change to user's home directory
For printer connections, another command, AddPrinterConnection, is available only for NT systems. This command can be used only to connect to printers on a server running under NT.

AddPrinterConnection adds a connection to the specified printer for the current user. The syntax is
AddPrinterConnection ("printer name")
When NT connects to the printer, it may copy printer driver files to the local computer. If the user doesn’t have permission to copy files to the appropriate location, AddPrinterConnection fails and @ERROR returns the following:
Here’s an example:
If AddPrinterConnection("\\printserver\hp laserjet 4") = 0
 ? "Added printer connection...."
As you’d expect, the DeletePrinterConnection command deletes a connection to a printer that was established by using AddPrinterConnection. As with AddPrinterConnection, this function is available only on NT. The DeletePrinterConnection function doesn’t delete any printer driver files that were copied from the server on which the printer resides when the printer connection was established.

File handling
One of the things you may want to do in a logon script is check settings on the PC and record them in a central location. Therefore, you need to read from and write to files. KiXtart provides simple file input/output (I/O) functions as well as functions to read and write.ini files.

The RedirectOutput function only allows writing to—not reading from—a file. The function simply redirects all screen output to a file. Its syntax is
RedirectOutput ("filename", overwrite)
where filename is a string that names the file to which to redirect the output and overwrite is an optional numeric value indicating whether to clear the output file before writing any data to it. If filename is an empty string (""), output is redirected to the screen. So, using RedirectOutput("") is a simple way of "closing" the file you were writing to. The overwrite parameter can have the following values:
  • 0—Appended to the existing contents of the file.
  • 1—All data in the file is overwritten when the output is redirected to the file.

If all output is redirected to a file, some commands that write to the screen, such as Cls, are ignored. Here’s an example:
If RedirectOutput(@WKSTA + ".log") = 0
 ? "Opened '" + @WKSTA + ".log' at " + @TIME ?
Sort of the opposite of RedirectOutput, the Display command displays the contents of a file, much like the TYPE command in DOS. The syntax of the Display command is
Display "filename"
This is a useful way of displaying instructions in the console. If you’ve hidden the console, you will, of course, need to unhide it if you intend for the user to read what’s displayed.

True file I/O is achieved using the functions Open, Close, ReadLine, and WriteLine. These functions process small configuration files and aren’t intended for larger operations, such as scanning long files.

The Open function allows you to specify whether to
  • Open a file for read or write access.
  • Create a new file or reuse one if a file exists with the same name.

The syntax for the Open function is
where filenumber is a numeric expression indicating the file number of the file to open (possible values range from 1 to 10); filename is a string expression indicating the path and name of the ASCII file to open; and mode is an optional parameter that indicates what should happen if the file doesn’t exist.

The mode parameter can have the following values:
  • 0—If the file doesn’t exist, Open fails with return code 2 (the default).
  • 1—If the file doesn’t exist, Open will create a new file.
  • 2—Opens the file for read access (the default).
  • 4—Opens the file for write access.

These values are cumulative. So, if you want to open a file for write access and create the file if it doesn’t yet exist, you should specify 5. Notice, however, that a file cannot be opened for read and write access (mode = 6) at the same time.

The Open function returns one of the following values:
  • 0—File opened successfully
  • -1—Invalid filename specified
  • -2—Invalid file number specified
  • -3—File number already in use
  • >0—System error

Here’s an example:
If Open(3, @LDRIVE + "\config\settings.txt") = 0
 ; Process the contents
When you’ve finished accessing a file you have previously opened, be sure to close it using the Close command. You may choose to leave the file open and it will be closed at the end of the script, but using the Close command is neater and will release filenumber for reuse. The syntax for the Close command is
The ReadLine function reads a string ending in a carriage return—that is, a line. If successful, the function returns the string without a carriage return. If it encounters an error, @ERROR returns one of the following error codes:
  • 0—Line read successfully
  • -1—End of file
  • -2—Invalid file number specified
  • -3—File number not open
  • -4—File not open for reading

The syntax for the ReadLine function is
$Line = ReadLine(filenumber)
Here’s an example of processing the contents of an ASCII file:
If Open(3, @LDRIVE + "\config\settings.txt") = 0
$x = ReadLine(3)
While @ERROR = 0
 ? "Line read: [" + $x + "]"
 $x = ReadLine(3)
The WriteLine function appends a line to the end of a file previously opened. If WriteLine encounters an error, @ERROR is set to one of these error codes:
  • 0—Line written successfully
  • -1—End of file
  • -2—Invalid file number specified
  • -3—File number not open
  • -4—File not open for writing

WriteLine doesn’t automatically append a carriage return, so if you want to write a carriage return, you should add it to the string (as in $LineToWrite + Chr(13) + Chr(10)).

The syntax for the WriteLine function is
WriteLine(filenumber, "text")
Here’s an example:
If Open(3, "C:\temp\logon.log",5) = 0
 $x = WriteLine(3, "KiXtart started at " + @TIME + Chr(13) + Chr(10))
 ? "Failed to open log file, error code : [" + @ERROR + "]"
Handling .ini files
If you’re familiar with .ini, or initialization files, you know that they have sections, denoted by section headers enclosed in square brackets. Each section can contain zero or more keys with values.

Many 16-bit applications use .ini files to store configuration details. The most common files you’ll find on Windows systems are Win.ini and System.ini. Any 32-bit applications store their information in the registry.

KiXtart provides two functions that allow you to process this type of file with ease, which makes it very simple for you to use .ini files instead of ASCII files. The functions are ReadProfileString and WriteProfileString.

The ReadProfileString function allows you to read in the value of any key in any section of a given .ini file. Its syntax is
ReadProfileString("filename", "section", "key")
where filename is the full name of the .ini file; section is a string that specifies the section containing the key name; and key represents a string containing the key name whose associated string is to be retrieved. If filename doesn’t include a full path, Windows searches for the file in the Windows directory. If section is empty, ReadProfileString returns all section names in the file. If key is empty, all key names in the section specified by section are returned. @ERROR is set to 0 if the function is successful or to the relevant error code if the function fails.

Here’s an example:
$ver = ReadProfileString(“Infoview.ini”,"SQLBOOKS.Settings", "licence_version")
If @ERROR = 0
 ? "SQL Books licence = " + $ver
Here’s the syntax for the WriteProfileString function:
where filename is a string identifying the .ini file; section is the name of the section of the .ini file where string is to be inserted; key is the name of the key to associate with string; and string is the string to write to the file.

If section doesn’t exist, the section is created. The section name is not case-sensitive, and it can contain any combination of uppercase and lowercase letters. If key doesn’t exist in the specified section, the key is created. If the parameter is empty, the entire section, including all entries within the section, is deleted. If string is empty, the key identified by key is deleted.
Be careful not to miss any of the parameters, because this will cause the key, or even the whole section, to be deleted.
Here’s an example:
$ver = WriteProfileString(“Infoview.ini”,"SQLBOOKS.Settings","licence_checked",@DATE)
If @ERROR <> 0
 ? "SQL Books licence check not logged. Error [" + @ERROR + "]"
In this installment, I’ve described how to manipulate the DOS window, or console, that KiXtart runs in. I also showed you how to communicate with a user, map network drives, and handle I/O both to the screen and files.

I’ve mentioned strings quite often in this Daily Drill Down, so in my next installment of this series, I’ll cover the commands and functions available in KiXtart for manipulating strings. I'll also describe some of the more useful functions that you may use in your early scripts.

Richard Charrington’s computer career began when he started working with PCs—back when they were known as microcomputers. Starting as a programmer, he worked his way up to the lofty heights of a Windows NT systems administrator, and he has done just about everything in between. Richard has been working with Windows since before it had a proper GUI and with Windows NT since it was LANManager. Now a contractor, he has slipped into script writing for Windows NT and has built some very useful auto-admin utilities.

The authors and editors have taken care in preparation of the content contained herein, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for any damages. Always have a verified backup before making any changes.

Editor's Picks

Free Newsletters, In your Inbox