V. vbs script library manual-creation, append, and deletion of text files

Source: Internet
Author: User
Tags time and date

 

Text files are a powerful system management tool for system administrators. This seems impossible for the current advanced graphic interface and multi-user operating systems. However, simple text files, such as NotePad files, are still a key element in system management. Text files are lightweight and easy to maintain. They occupy less disk space and do not need additional software support. Text files can work easily and can be carried easily. A script file written in a text file can be copied and viewed on any computer, even though it is not running on Windows. in addition, it provides a fast, simple, and standard way to input and output data to the script. Text files can store the input data arguments in the script) or hard encoding in the script. In this way, you do not need to enter the name of the 100 servers in the command line. The script can read this information from a text file. Similarly, text files provide a quick and easy way to store the information obtained by scripts. The data can be directly written to the database, but this requires additional configuration on the server, additional script code, and additional management during script running. However, the data can be stored in a text file and then imported to the data later. FSO provides some methods to read and write text files.


Creating text files

FSO allows you to work with existing texts or create scripts on your own. To create a new text file, create a FSO object, call the createtextfile method, and enter the complete file path information as the parameter of this method.

For example, the following script code creates a scriptlog.txt file in the C:/FSO Folder:

1 Set objfso = Createobject ("scripting. FileSystemObject ")

2 set objfile = objfso. createtextfile ("C:/FSO/scriptlog.txt ")

If this file exists, the createtextfile method creates one. If this file already exists, the createtextfile method will re-write the existing text file and replace it with a new blank file. If you want this file not to be replaced, you can use a parameter with overwrite options. When this parameter is set to false, the saved files are not rewritten. If this parameter is set to true (the default value is true), the existing file will be rewritten. For example, the following script will not be rewritten if the created file exists.

Set objfile = objfso. createtextfile ("C:/FSO/scriptlog.txt", false)

If you set the parameter to false and the file exists, a running error occurs. In this case, you can check whether a file exists. If yes, perform other operations, such as allowing users to change a new file name.

Creating file names within the script

To prevent file errors, use a script to generate a name for the text file. Because the file name generator does not create a meaningful name, this is not a good way for you to name logs and other files in the future. However, this ensures a specific file name for scripts that require temporary files. For example, you may want your script to save the data in HTML or XML format, display the data in a Web browser, and delete the temporary file when the web browser is disabled. In this case, you can use the gettempname method to generate a unique file name.

To generate a special file name, the script first needs to create an fso object instance and then call the gettempname method (No parameter is required .) For example, the script in 4.33 uses a for next loop to randomly generate 10 file names.

1 Set objfso = Createobject ("scripting. FileSystemObject ")

2 for I = 1 to 10

3 strtempfile = objfso. gettempname

4 wscript. Echo strtempfile

5 next

The name of the file generated using gettempname is not unique. This is partly because of the algorithm used to generate the name, but partly because the number of possible names is limited. The file name is limited to 8 bytes, and the first three bytes are set to rad. For example, you can use your scripts to create the first 10000 file names, after 9,894th file names, they are no longer unique, and the remaining 106 53 pairs are copied.

The sample script in 4.34 uses the gettempname method to create an object. The script must:

1. Create an fso object instance.

2. Create a variable for the folder C:/FSO called strpath.

3. Use the gettempname method to generate a separate sub-file name.

4. Use the buildpath method to combine the folder name and file name to create a complete temporary file name. The entire path is stored in the strfullname variable.

5. Call the createtextfile method and use strfullname as the parameter.

6. close the file after it is created. In a production environment, in most cases, you may need to write data to it before closing it.

1 Set objfso = Createobject ("scripting. FileSystemObject ")

2 strpath = "C:/FSO"

3 strfilename = objfso. gettempname

4 strfullname = objfso. buildpath (strpath, strfilename)

5 set objfile = objfso. createtextfile (strfullname)

6 objfile. Close

 

Opening text files

There are three main steps to work with text files. Before you can do anything else, you must open a text file. You can open an existing file or create a new text file. After the file is created, it is opened by default. Each method returns a textstream object instance.

After obtaining the textstream object, you can write or read the object to the file. However, you cannot read or write data to the same file. In other words, in the same operation, you cannot open a file, read the file, and then write to it. You must close the file after reading it, open the file, write data, and close it.

When you open an existing file, the file is either ready to be read or written. If you create a new text file, the file is only read, and there is no other reason for it to be read. Finally, you need to close the text file. Although it is not necessary, it will automatically close at the end of the script, but this is a good method for program practice.

To open a text file:

1. Create an fso object instance.

2. Use: opentextfile to open a text file. This opentextfile requires two parameters: one is the path of a file and the other is the following parameter:

For reading (parameter value = 1, constant = forreading ).

After the file is opened, it is used to prepare for reading. To write the file, you must open the file again with the forwriting or forappending parameter.

For writing (parameter value 2, constant = forwriting ).

The file is opened and the written data overwrites the existing data. This means that the old data is deleted and the new data is added. Use this method to replace existing data with new data.

For appending (parameter value 8, constant = forappending ).

Open the file in this mode and add new data to the end of the file. Use this method to add new data to an existing file.

When opening a file, you must use the appropriate parameters. When you open a file in Read mode and try to write something into it, you will receive a bad file Mode

. If you try to open a non-text file, you will receive the same error. You can directly use a value (for example, 1 stands for writing) or create a constant and assign it an appropriate value. For example, either of the following methods can open a file and be read:

Const forreading = 1

Set objfso = Createobject ("scripting. FileSystemObject ")

Set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", forreading)

Set objfile2 = objfso. opentextfile ("C:/FSO/scriptlog2.txt", 1)

However, when this constant is not defined, you cannot use it directly. This is because the VB script does not actually have these COM Object constants. The following script returns an invalid procedure call or argument error and fails. This is because the constant forreading is not explicitly defined. Because it is not defined, this variable is assigned 0 by default, and 0 is not a legal parameter for opentextfile:

Set objfso = Createobject ("scripting. FileSystemObject ")

Set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", forreading)

In the script in 4.35, C:/FSO/scriptlog.txt is opened to prepare for reading. The User-Defined variables are used and assigned a value of 1.

Listing 4.35 opening a text file for reading

1 const forreading = 1

2 set objfso = Createobject ("scripting. FileSystemObject ")

3 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", forreading)

 

Closing text files

All text files opened by scripts are automatically closed when the script ends. Because of this, it is not necessary to explicitly close a text file. However, closing this text file is a good program practice. In the following situations, if you do not close the file, some errors may occur.

 

 

Reread the file.

Sometimes you may want to use a script to read a file multiple times. You may open a text file, save all its content to a string variable, and search for the string to find the specific error code. When this error is found, you can read the file row by row and extract each row with the error. If you try to read a file multiple times, you will encounter a running error instead of receiving the expected result. For example, the following script reads a text file, returns the content of the file to the screen, and then triesRepeatedThis process:

Set objfso = Createobject ("scripting. FileSystemObject ")

Set objfso = Createobject ("scripting. FileSystemObject ")

Set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", 1)

Wscript. Echo "reading file the first time :"

Strcontents = objfile. readall

Wscript. Echo strcontents

Wscript. Echo "reading file the second time :"

Do While objfile. atendofstream = false

Strline = objfile. Readline

Wscript. Echo strline

Loop

The command line information when running in cscript is as follows:

Reading file the first time:

File Line 1.

File Line 2.

File line 3.

Reading file the second time:

The first file is read, and the content is stored in the variable strcontents. The second time, when the file is read, nothing is displayed on the screen, this is because the file has reached the end of the file and no other data is read to you. To read the data, you must close the file and open it again. You cannot jump to the beginning of the file after reading the end of the file. The textstreamobject. Close method is used to close a text file. For example, in script 4.36, create an fso object instance, open a text file, and close it immediately. To access the file content, you must call the opentextfile method again to re-open the file.

Listing 4.36 opening and closing a text file

1 Set objfso = Createobject ("scripting. FileSystemObject ")

2 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", 1)

3 objfile. Close

 

Reading text files

In many enterprise scripts, reading text files is a standard process. You can use this function to read command line parameters. For example, if your text file contains a list of computer names, the script is audited to read the list, and then runs the script on each computer. Search for log files that meet specific conditions. For example, you may want to find all the logs with errors. Add content to the log file and import it to the database. For example, you may have a service or program to save information to a specific format of saved text files. Then, you can use your scripts to read the file and copy the relevant information to the database.

You can use FSO to read the content of a text file. However, you must note that FSO can only read ASCII text files. You cannot use FSO to read Unicode or

Binary files, such as Microsoft Word or Microsoft Excel. When reading text files with FSO, you can only use one of the following methods: from front to back. In addition, FSO reads files row by row. If you try to return the previous row, you must read it again from the beginning until the Specific Row.

You cannot open a file for reading and writing at the same time. If you open a file to read, you want to modifyFile ContentYou must re-open the file. If you try to read files in write mode, you will receive a bad file mode error.

It is also a common technique to read and stop specific characters. For example, the following command reads the first 12 characters of Alerter. Shar in the first line and assigns it to the variable.

Strtext, and then stop: strtext = objtextfile. Read (12)

Readline reads the information of each row in a text file and stops when it reaches the new row. For example, the following command reads the first line and assigns it to the variable strtext, and then stops. Strtext = objtextfile. Readline

To read the content of the entire file row by row, put Readline in a loop.

Readall reads the entire contents of a text file into a variable.

The Skip skips a specified number of characters and stops. For example, the following command line skips the first 12 bytes, and subsequent operations start with 13th characters.

Objtextfile. Skip (12)

Skipline skips a whole line. For example, the following code first reads the first line and then the third line. Skip the second line

Strtext = objtextfile. Readline

Objtextfile. skipline

Strtext = objtextfile. Readline

Although it is very easy to find something in a single string, it is not very fast. When reading nearly 6000 lines of test files using the readall method, the system searches for about KB per second. If you read data row by row, it will be less than one minute.

To use the readall method, open a text file and call the readall method (without parameters). For example, in the script 4.38, open the file C:/FSO/scriptlog.txt, then read the content of the file. Jiang data is stored in the variable strcontents. The script then displays the value of this variable, that is, the content of the text file.

Listing 4.38 reading a text file using the readall Method

1 const forreading = 1

2 set objfso = Createobject ("scripting. FileSystemObject ")

3 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", forreading)

4 strcontents = objfile. readall

5 wscript. Echo strcontents

6 objfile. Close

Reading a text file line by line

For the purpose of system management, text files sometimes work like a flat database. Each row represents a record of the database. For example, scripts often read server names in text files and then perform operations on these servers. In these cases, the text file looks similar to the following:

 

Atl-dc-01

Atl-dc-02

Atl-dc-03

Atl-dc-04

When a text file is used as a flat database, the script is used to read each record and then perform some work on each record. For example, a script may read the first computer name and connect it to implement some functions. Then the script reads the name of the second computer, connects to it, and implements the same function. This process ends after all the computer names are read.

The Readline method allows your script to read a single row in a text file. For this purpose, open a text file, and then use a do loop until the file's

The atendofstream attribute is true. In this loop, call Readline

Method, store the content of the first line to a variable, and then perform some actions. When the script executes the loop, it automatically discards the content of the first row to read the content of the second row to this variable. This process continues until the end of the file.

For example, in script 4.39, open the file C:/FSO/serverlist.txt and read the entire file line by line to display the content on the screen:

Listing 4.39 reading a text file using the Readline Method

1 Set objfso = Createobject ("scripting. FileSystemObject ")

2 set objfile = objfso. opentextfile ("C:/FSO/serverlist.txt", 1)

3 do until objfile. atendofstream

4 strline = objfile. Readline

5 wscript. Echo strline

6 Loop

7 objfile. Close

"Reading" a text file from the bottom to the top

As mentioned above, FSO can only be read from the front of a text file, and you cannot read from the front. This has some problems with log files. Most log files are written in the date format, and the first log is recorded in the first line, the second record is in the second row, and so on. This means that the latest logs are always at the end of the file.

Sometimes you want to display information in the reverse date order, that is, the latest record is first displayed, and the oldest record is last shown. Although you cannot read text files from the back end, to achieve the above purpose, the script must:

1. Create an array to store each row of text files

2. Read the information of each row of a text file using Readline, and store the information of each row as an independent element of the array in the array.

3. display the array information on the screen, starting from the last side of the array and displaying it forward.

For example, the script in 4.40 reads the information of the file C:/FSO/scriptlog.txt, and then uses the information of each row as an array.

An element is stored in the array arrfileline. After the entire file is read, the array information is displayed from the last one of the arrays. To do this, a

Loop, from the last element of the array, the upper bound of array gradually increases to the first element, the lower bound of Array

1 dim arrfilelines ()

2 I = 0

3 set objfso = Createobject ("scripting. FileSystemObject ")

4 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", 1)

5 do until objfile. atendofstream

6 redim preserve arrfilelines (I)

7 arrfilelines (I) = objfile. Readline

8 I = I + 1

9 Loop

10 objfile. Close

11 For L = ubound (arrfilelines) to lbound (arrfilelines) step-1

12 wscript. Echo arrfilelines (l)

13 next

If the file content is the same as the following:

6/19/2002 success

6/20/2002 failure

6/21/2002 failure

6/22/2002 failure

6/23/2002 success

The echo information on the screen is as follows:

6/23/2002 success

6/22/2002 failure

6/21/2002 failure

6/20/2002 failure

6/19/2002 success

Reading a text file character by character

 

 

 

In some fixed-width text files, the area is restricted by the length. The first field1 may contain 15 bytes, and the first 2nd fields may contain 10, and so on. The file looks similar to the following:

Server value status

Atl-dc-0119345 OK

Atl-printserver-02 00042 OK

Atl-win2kpro-0500000 failed

In some cases, you may only want to obtain the value of values or the status information. The value information is easy to indicate. Values always starts from 26th

It cannot exceed 5 characters. To obtain these values, you only need to obtain information of characters 26, 27, 28, 29, and 30.

The read method allows you to read a specified number of bytes. Its individual parameter is the number of bytes to read. For example, the following script code example reads the next seven bytes and saves the read value to the variable strcharacters:

Strcharacters = objfile. Read (7)

Using the Skip and skipline methods, you can obtain the specific characters you select in a text file. For example, in script 4.41, only 6th bytes of each row are read. To do this, the script must:

1. Skip the first five bytes of each line using skip (5)

2. Use read (1) to read 6th bytes

3. Jump to the following line.

Listing 4.41 reading a fixed-width text file

1 Set objfso = Createobject ("scripting. FileSystemObject ")

2 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", 1)

3 do until objfile. atendofstream

4 objfile. Skip (5)

5 strcharacters = objfile. Read (1)

6 wscript. Echo strcharacters

7. objfile. skipline

8 Loop

To better illustrate how the script works, we assume that the script file C:/FSO/scriptlog.txt looks like the following:

Xxxxx1xxxxxxxxxxxxxx

Xxxxx2xxxxxxxxxxxxxxxxxxx

Xxxxx3xxxxxxxxxxxxx

Xxxxx4xxxxxxxxxxxxxxxxxxxxxxxxx

For each row of this file, the first five characters are X, the sixth is a number, and the last is a random number of X. When script 4.41 is run, the script will:

1. Open the text file and start reading from the first line.

2. Skip the first five characters.

3. Read the sixth character using the read Method

4. Echo characters on the screen

5. Jump to the following lineRepeatedThe above process is finished until the script is running ..

Writing to text files

Writing data in text files is another powerful function of writing system management scripts. A text file provides a way to store the input obtained by the script. Input can replace the existing text or add it to the end of the existing text. Text files can also record the execution of scripts. This is useful for debugging scripts. Place the script execution record in a text file. You can view the log for a while to determine which scripts are actually executed and which ones are not executed. FSO provides you with the ability to write data to text files. To use the FSO script to write data to a text file, you must:

1. Create an fso object instance.

2. Use the opentextfile method to open this text file. You can open it in two ways:

For writing (parameter value 2, constant = forwriting ).

In this mode, new data will overwrite old data. (Old data will be deleted and new data will be added .)

This mode is used to replace existing files with new content.

For appending (parameter value 8, constant = forappending ).

In this mode, data is written at the end of the original file. Add data to an existing file in this mode.

3. Use the write, writeline, and writeblankline methods to write data to text files.

4. Close text files

There are three methods to write data to a text file in table 4.9:

Table 4.9 write methods available to the FileSystemObject

Method description

Write writes data to a text file instead of adding the file to the end. Does not wrap automatically.

For example, the following code writes two separate strings:

Objfile. Write ("this is line 1 .")

Objfile. Write ("this is Line 2 .")

Methoddescription

The returned data is similar to the following:

This is line 1. This is Line 2.

Writeline adds a line feed symbol after writing data to a text file, and then automatically wrap the line.

For example, the following code:

Objfile. writeline ("this is line 1 .")

Objfile. writeline ("this is Line 2 .")

The output result is as follows:

This is Line 1.

This is Line 2.

Writeblanklines writes a specified number of blank rows to a text file. For example, the following code writes two lines of independent text to a text file and then separates them with blank lines:

Objfile. writeline ("this is line 1 .")

Objfile. writeblanklines (1)

Objfile. writeline ("this is Line 2 .")

The output result is as follows:

This is Line 1.

This is Line 2.

In addition to the methods in table 4.9, the VB script provides the constant vbtab to write data to text files. Vbtab

Insert a space into two characters. To create a space-separated file, the code is similar to the following:

Objtextfile. writeline (objservice. displayname & vbtab & objservice. State)

One weakness of FSO is that it cannot directly modify the information of specific rows. You cannot write a command like the following: Skip to the fifth line, change some data, and save it as a new file. Your script must be

1. Read the entire 10 rows

2. Write lines 1-4 back to the file.

3. Write the modified content of the fifth line.

4. Write the content from 6th rows to 10th rows.

 

Overwriting existing data

In system management, conciseness is a virtue. For example, if your script runs every night and obtains logs from Event Logs On Your DC, write these events to the database, and record which computer can be successfully connected, no. For some historical purposes, you may wish to keep track of all the successes and failures of the next year. This is important when the script takes effect and the network is unstable. In other cases, you may just want to see what happened when the script was running. In other words, you do not want the last 365 days in a log, but the latest information. It allows you to quickly open the file and check whether the script runs as scheduled.

When your text file is opened in forwriting mode, any new data written will replace the existing file. For example, if your text file stores the complete set of Shakespeare stories, but you open the text in forwriting mode using the script and write a letter a to it, after you close the file, it only contains the letter A, and all the original data is lost.

This script opens the script C:/FSO/scriptlog.txt in forwriting mode and writes the current date and time to the file. Every time a script is run, the old time and date are replaced by a new one. This text file always has a separate date value.

Listing 4.42 overwriting existing data

1 const forwriting = 2

2 set objfso = Createobject ("scripting. FileSystemObject ")

3 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", forwriting)

4 objfile. Write now

5 objfile. Close

Appending new data to existing data

Many scripts are designed to run at specific time intervals, receive data, and save data. These scripts are used to analyze the trend or usage in the past. In these cases, you do not want to delete existing data to replace the new data.

For example, if you use your script to monitor the process usage. At any time point, the process usage should be a value between 0 and 100. for itself, a single value is meaningless. You needRepeatedConstantly monitors usage and records its values. If the data returned by your process within several seconds is 9%, 17%, 92%, 90%, 79%, 88%, 91%, your process is very high. In this way, we can compare the usage in this period.

If you open a file in forappending mode, you can make the data not overwrite the existing data, and its data is added to the bottom of the file. For example, a script in 4.43 opens a text file and writes the current date and time to the file. Because it is based on forappending

The current date will unload the bottom of the file. If you run the scripts separately at different times, your script ends with the following information:

6/25/2002 8:49:47 AM

6/25/2002 8:49:48 AM

6/25/2002 8:50:33 AM

6/25/2002 8:50:35 AM

Listing 4.43 appending data to a text file

1 const forappending = 8

2 set objfso = Createobject ("scripting. FileSystemObject ")

3 set objfile = objfso. opentextfile ("C:/FSO/scriptlog.txt", forappending)

4 objfile. writeline now

5 objfile. Close

The preceding script writes data using the writeline method to ensure that each date excludes one row. If this script uses write

When the script is running, the data is written together as follows:

6/25/2002 8:49:47 am6/25/2002 8:49:48 am6/25/2002 8:50:33 am6/25/2002 8:50:35 AM

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.