Book Image

Getting Started with Powershell

Book Image

Getting Started with Powershell

Overview of this book

Table of Contents (19 chapters)
Getting Started with PowerShell
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Next Steps
Index

Reading and writing text files


One method of reading a text file in PowerShell is to use the Get-Content cmdlet. Get-Content outputs the contents of the file as a collection of strings. If we have a text file called Servers.txt that contains the names of the SQL Servers in our environment, we would use the following code to read the file and get the status of the MSSQLSERVER service on the servers. Note that with this code, the file will not contain anything but the server names, each on a separate line with no blank lines:

If you don't want the file to be split into lines, there is a –Raw switch parameter that causes the cmdlet to output the entire file as a single string. As an example, if we have a text file with three lines, we can see the difference between when we use the default operation and when we use –Raw by counting the number of strings returned:

If you want only the beginning or the end of the file, you could use Select-Object with the –First or –Last parameters, but it turns...