Chapter 9. Reading and Writing Files

Now that you know how to manage files and folders, you're ready to take a closer look at manipulating the contents of files. Many different methods and properties are available for working with files. But before you can work with a file, you need to open it for reading, writing, or appending.

Note

Some of the scripts in this chapter are not fully working examples. The scripts may only highlight the syntax of how the commands could be used in a complete script. Also, you may need to replace files and file paths with your own if you are trying the examples on your own computer.

Opening Files

Two methods are provided for opening files. You can use the OpenTextFile method of FileSystemObject or the OpenAsTextStream method of the File object. While both methods return a TextStream object, they are used in slightly different ways.

Using OpenTextFile

The OpenTextFile method expects to be passed the full path to the file you want to open, such as:

VBScript

Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile("D:\data\log.txt")

JScript

var fs = new ActiveXObject("Scripting.FileSystemObject");
var ts = fs.OpenTextFile("D:\\data\\log.txt")

If you plan to work with the file, you should set the access mode as well. Three access modes are provided:

  • 1: Opens a file for reading. Associated constant is ForReading.

  • 2: Opens a file for writing to the ...

Get Microsoft® PowerShell, VBScript and JScript® Bible now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.