O'Reilly logo

Windows PowerShell Cookbook, 3rd Edition by Lee Holmes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. Simple Files

Introduction

When administering a system, you naturally spend a significant amount of time working with the files on that system. Many of the things you want to do with these files are simple: get their content, search them for a pattern, or replace text inside them.

For even these simple operations, PowerShell’s object-oriented flavor adds several unique and powerful twists.

Get the Content of a File

Problem

You want to get the content of a file.

Solution

Provide the filename as an argument to the Get-Content cmdlet:

PS > $content = Get-Content c:\temp\file.txt

Place the filename in a ${} section to use the cmdlet Get-Content variable syntax:

PS > $content = ${c:\temp\file.txt}

Provide the filename as an argument to the ReadAllLines() or ReadAllText() methods to use the System.IO.File class from the .NET Framework:

PS > $content = Get-Content c:\temp\file.txt -Raw
PS > $contentLines = [System.IO.File]::ReadAllLines("c:\temp\file.txt")

Discussion

PowerShell offers three primary ways to get the content of a file. The first is the Get-Content cmdlet—the cmdlet designed for this purpose. In fact, the Get-Content cmdlet works on any PowerShell drive that supports the concept of items with content. This includes Alias:, Function:, and more. The second and third ways are the Get-Content variable syntax and the ReadAllText() method.

When working against files, the Get-Content cmdlet returns the content of the file line by line. When it does this, PowerShell supplies additional ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required