Chapter 8. Structured Files

8.0. Introduction

In the world of text-only system administration, managing structured files is often a pain. For example, working with (or editing) an XML file means either loading it into an editor to modify by hand, or writing a custom tool that can do that for you. Even worse, it may mean modifying the file as though it were plain text while hoping to not break the structure of the XML itself.

In that same world, working with a file in CSV format means going through the file yourself, splitting each line by the commas in it. It’s a seemingly great approach, until you find yourself faced with anything but the simplest of data.

Structure and structured files don’t come only from other programs, either. When writing scripts, one common goal is to save structured data so that you can use it later. In most scripting (and programming) languages, this requires that you design a data structure to hold that data, design a way to store and retrieve it from disk, and bring it back to a usable form when you want to work with it again.

Fortunately, working with XML, CSVs, and even your own structured files becomes much easier with PowerShell at your side.

8.1. Access Information in an XML File

Problem

You want to work with and access information in an XML file.

Solution

Use PowerShell’s XML cast to convert the plain-text XML into a form that you can more easily work with. In this case, the RSS feed downloaded from the Windows PowerShell blog:

 PS >$xml = [xml] (Get-Content ...

Get Windows PowerShell Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.