Windows PowerShell Cookbook SECOND EDITION Windows PowerShell Cookbook Lee Holmes Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo Windows PowerShell Cookbook, Second Edition by Lee Holmes Copyright © 2010 Lee Holmes. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editor: Mike Hendrickson Indexer: Newgen North America, Inc. Production Editor: Teresa Elsey Cover Designer: Karen Montgomery Copyeditor: Genevieve d’Entremont Interior Designer: David Futato Proofreader: Teresa Elsey Illustrator: Robert Romano Printing History: October 2007: First Edition. August 2010: Second Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Windows PowerShell Cookbook, the image of a box turtle, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-0-596-80150-2 [M] 1281554603 Table of Contents Foreword .................................................................. xvii Foreword to the First Edition .................................................. xxi Preface .................................................................... xxv Part I. Tour A Guided Tour of Windows PowerShell ........................................... 3 Part II. Fundamentals 1. The Windows PowerShell Interactive Shell ................................. 19 1.1 Run Programs, Scripts, and Existing Tools 19 1.2 Resolve Errors Calling Native Executables 21 1.3 Run a PowerShell Command 23 1.4 Invoke a Long-Running or Background Command 24 1.5 Notify Yourself of Job Completion 27 1.6 Customize Your Shell, Profile, and Prompt 28 1.7 Find a Command to Accomplish a Task 31 1.8 Get Help on a Command 32 1.9 Program: Search Help for Text 34 1.10 Program: View PowerShell’s HTML Help 36 1.11 Launch PowerShell at a Specific Location 37 1.12 Invoke a PowerShell Command or Script from Outside PowerShell 38 1.13 Customize the Shell to Improve Your Productivity 40 1.14 Program: Learn Aliases for Common Commands 42 1.15 Program: Learn Aliases for Common Parameters 44 1.16 Access and Manage Your Console History 46 1.17 Program: Create Scripts from Session History 48 v 1.18 Invoke a Command from Your Session History 49 1.19 Program: Search Formatted Output for a Pattern 51 1.20 Interactively View and Process Command Output 52 1.21 Store the Output of a Command into a File 54 1.22 Add Information to the End of a File 55 1.23 Record a Transcript of Your Shell Session 55 1.24 Extend Your Shell with Additional Commands 56 1.25 Use Commands from Customized Shells 57 1.26 Save State Between Sessions 59 2. Pipelines ............................................................. 63 2.1 Filter Items in a List or Command Output 64 2.2 Group and Pivot Data by Name 65 2.3 Program: Simplify Most Where-Object Filters 68 2.4 Program: Interactively Filter Lists of Objects 70 2.5 Work with Each Item in a List or Command Output 72 2.6 Automate Data-Intensive Tasks 74 2.7 Program: Simplify Most Foreach-Object Pipelines 78 2.8 Intercept Stages of the Pipeline 80 2.9 Automatically Capture Pipeline Output 81 2.10 Capture and Redirect Binary Process Output 83 3. Variables and Objects ................................................... 89 3.1 Display the Properties of an Item as a List 90 3.2 Display the Properties of an Item as a Table 92 3.3 Store Information in Variables 94 3.4 Access Environment Variables 95 3.5 Program: Retain Changes to Environment Variables Set by a Batch File 98 3.6 Control Access and Scope of Variables and Other Items 100 3.7 Program: Create a Dynamic Variable 102 3.8 Work with .NET Objects 104 3.9 Create an Instance of a .NET Object 108 3.10 Program: Create Instances of Generic Objects 110 3.11 Reduce Typing for Long Class Names 113 3.12 Use a COM Object 115 3.13 Learn About Types and Objects 115 3.14 Get Detailed Documentation About Types and Objects 117 3.15 Add Custom Methods and Properties to Objects 119 3.16 Create and Initialize Custom Objects 121 3.17 Add Custom Methods and Properties to Types 125 vi | Table of Contents 4. Looping and Flow Control .............................................. 131 4.1 Make Decisions with Comparison and Logical Operators 131 4.2 Adjust Script Flow Using Conditional Statements 133 4.3 Manage Large Conditional Statements with Switches 135 4.4 Repeat Operations with Loops 136 4.5 Add a Pause or Delay 139 5. Strings and Unstructured Text .......................................... 141 5.1 Create a String 141 5.2 Create a Multiline or Formatted String 143 5.3 Place Special Characters in a String 144 5.4 Insert Dynamic Information in a String 144 5.5 Prevent a String from Including Dynamic Information 146 5.6 Place Formatted Information in a String 147 5.7 Search a String for Text or a Pattern 148 5.8 Replace Text in a String 151 5.9 Split a String on Text or a Pattern 152 5.10 Combine Strings into a Larger String 154 5.11 Convert a String to Upper/Lowercase 156 5.12 Trim a String 157 5.13 Format a Date for Output 158 5.14 Program: Convert Text Streams to Objects 160 5.15 Generate Large Reports and Text Streams 164 5.16 Generate Source Code and Other Repetitive Text 166 6. Calculations and Math ................................................. 171 6.1 Perform Simple Arithmetic 171 6.2 Perform Complex Arithmetic 173 6.3 Measure Statistical Properties of a List 175 6.4 Work with Numbers as Binary 177 6.5 Simplify Math with Administrative Constants 180 6.6 Convert Numbers Between Bases 181 7. Lists, Arrays, and Hashtables ............................................ 183 7.1 Create an Array or List of Items 183 7.2 Create a Jagged or Multidimensional Array 185 7.3 Access Elements of an Array 186 7.4 Visit Each Element of an Array 188 7.5 Sort an Array or List of Items 189 7.6 Determine Whether an Array Contains an Item 190 7.7 Combine Two Arrays 191 7.8 Find Items in an Array That Match a Value 192 7.9 Compare Two Lists 193 Table of Contents | vii 7.10 Remove Elements from an Array 193 7.11 Find Items in an Array Greater or Less Than a Value 194 7.12 Use the ArrayList Class for Advanced Array Tasks 195 7.13 Create a Hashtable or Associative Array 197 7.14 Sort a Hashtable by Key or Value 198 8. Utility Tasks .......................................................... 201 8.1 Get the System Date and Time 201 8.2 Measure the Duration of a Command 202 8.3 Read and Write from the Windows Clipboard 203 8.4 Generate a Random Number or Object 206 8.5 Program: Search the Windows Start Menu 208 8.6 Program: Show Colorized Script Content 209 Part III. Common Tasks 9. Simple Files .......................................................... 217 9.1 Get the Content of a File 217 9.2 Search a File for Text or a Pattern 219 9.3 Parse and Manage Text-Based Logfiles 222 9.4 Parse and Manage Binary Files 224 9.5 Create a Temporary File 227 9.6 Search and Replace Text in a File 228 9.7 Program: Get the Encoding of a File 231 9.8 Program: View the Hexadecimal Representation of Content 233 10. Structured Files ....................................................... 237 10.1 Access Information in an XML File 237 10.2 Perform an XPath Query Against XML 240 10.3 Convert Objects to XML 242 10.4 Modify Data in an XML File 243 10.5 Easily Import and Export Your Structured Data 245 10.6 Store the Output of a Command in a CSV or Delimited File 247 10.7 Import CSV and Delimited Data from a File 248 10.8 Use Excel to Manage Command Output 249 10.9 Parse and Interpret PowerShell Scripts 251 11. Code Reuse .......................................................... 255 11.1 Write a Script 255 11.2 Write a Function 258 11.3 Find a Verb Appropriate for a Command Name 260 11.4 Write a Script Block 261 viii | Table of Contents
Description: