www.it-ebooks.info Windows PowerShell Cookbook ™ www.it-ebooks.info Other Microsoft .NET resources from O’Reilly Related titles Windows PowerShell Quick Reference Windows Server 2008: The Definitive Guide Windows Vista Administration Windows Vista: The Definitive Guide .NET Books Resource Center dotnet.oreilly.com is a complete catalog of O’Reilly’s books on .NET and related technologies, including sample chapters and code examples. ONDotnet.com provides independent coverage of fundamental, interoperable, and emerging Microsoft .NET programming and web services technologies. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit con- ferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online refer- ence library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim- ply flip to the page you need. Try it today for free. www.it-ebooks.info Windows PowerShell Cookbook ™ Lee Holmes Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo www.it-ebooks.info Windows PowerShell Cookbook ™ by Lee Holmes Copyright © 2008 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 (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: John Osborn Production Editor: Laurel R.T. Ruma Production Services: Tolman Creek Design Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrators: Robert Romano and Jessamyn Read Printing History: October 2007: First 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 author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This book uses RepKover ™ , a durable and flexible lay-flat binding. ISBN-10: 0-59652-849-3 ISBN-13: 978-0-596-652849-2 [M] www.it-ebooks.info v Table of Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi Part I. Tour A Guided Tour of Windows PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Introduction 3 An Interactive Shell 4 Structured Commands (Cmdlets) 6 Deep Integration of Objects 7 Administrators As First-Class Users 8 Composable Commands 9 Techniques to Protect You from Yourself 9 Common Discovery Commands 10 Ubiquitous Scripting 11 Ad Hoc Development 12 Bridging Technologies 12 Namespace Navigation Through Providers 14 Much, Much More 16 Part II. Fundamentals 1. The Windows PowerShell Interactive Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.0 Introduction 19 1.1 Run Programs, Scripts, and Existing Tools 19 1.2 Run a PowerShell Command 21 www.it-ebooks.info vi | Table of Contents 1.3 Customize Your Shell, Profile, and Prompt 22 1.4 Find a Command to Accomplish a Task 25 1.5 Get Help on a Command 26 1.6 Program: Search Help for Text 28 1.7 Invoke a PowerShell Script From Outside PowerShell 29 1.8 Program: Retain Changes to Environment Variables Set by a Batch File30 1.9 Get the System Date and Time 32 1.10 Determine the Status of the Last Command 33 1.11 Measure the Duration of a Command 34 1.12 Customize the Shell to Improve Your Productivity 35 1.13 Program: Learn Aliases for Common Commands 36 1.14 Access and Manage Your Console History 38 1.15 Store the Output of a Command into a File 39 1.16 Add Information to the End of a File 41 1.17 Record a Transcript of Your Shell Session 41 1.18 Display the Properties of an Item As a List 42 1.19 Display the Properties of an Item As a Table 42 1.20 Manage the Error Output of Commands 44 1.21 Configure Debug, Verbose, and Progress Output 45 1.22 Extend Your Shell with Additional Snapins 47 1.23 Use Console Files to Load and Save Sets of Snapins 48 2. Pipelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 2.0 Introduction 49 2.1 Filter Items in a List or Command Output 50 2.2 Program: Simplify Most Where-Object Filters 51 2.3 Program: Interactively Filter Lists of Objects 52 2.4 Work with Each Item in a List or Command Output 54 2.5 Automate Data-Intensive Tasks 56 3. Variables and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 3.0 Introduction 61 3.1 Store Information in Variables 62 3.2 Access Environment Variables 63 3.3 Control Access and Scope of Variables and Other Items 65 3.4 Work with .NET Objects 67 3.5 Create an Instance of a .NET Object 71 3.6 Program: Create Instances of Generic Objects 73 3.7 Reduce Typing for Long Class Names 74 www.it-ebooks.info Table of Contents | vii 3.8 Use a COM Object 76 3.9 Learn About Types and Objects 77 3.10 Get Detailed Documentation About Types and Objects 78 3.11 Add Custom Methods and Properties to Objects 80 3.12 Add Custom Methods and Properties to Types 82 4. Looping and Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 4.0 Introduction 87 4.1 Make Decisions with Comparison and Logical Operators 87 4.2 Adjust Script Flow Using Conditional Statements 89 4.3 Manage Large Conditional Statements with Switches 90 4.4 Repeat Operations with Loops 91 4.5 Add a Pause or Delay 93 5. Strings and Unstructured Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 5.0 Introduction 95 5.1 Create a String 95 5.2 Create a Multiline or Formatted String 97 5.3 Place Special Characters in a String 98 5.4 Insert Dynamic Information in a String 99 5.5 Prevent a String from Including Dynamic Information 100 5.6 Place Formatted Information in a String 101 5.7 Search a String for Text or a Pattern 102 5.8 Replace Text in a String 105 5.9 Convert a String to Upper/Lowercase 106 5.10 Trim a String 107 5.11 Format a Date for Output 108 5.12 Program: Convert Text Streams to Objects 110 5.13 Generate Large Reports and Text Streams 114 6. Calculations and Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 6.0 Introduction 117 6.1 Perform Simple Arithmetic 117 6.2 Perform Complex Arithmetic 119 6.3 Measure Statistical Properties of a List 121 6.4 Work with Numbers As Binary 123 6.5 Simplify Math with Administrative Constants 127 6.6 Convert Numbers Between Bases 128 www.it-ebooks.info viii | Table of Contents Part III. Common Tasks 7. Simple Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7.0 Introduction 133 7.1 Get the Content of a File 133 7.2 Search a File for Text or a Pattern 135 7.3 Parse and Manage Text-Based Logfiles 136 7.4 Parse and Manage Binary Files 139 7.5 Create a Temporary File 141 7.6 Search and Replace Text in a File 143 8. Structured Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 8.0 Introduction 147 8.1 Access Information in an XML File 147 8.2 Perform an XPath Query Against an XML File 150 8.3 Modify Data in an XML File 151 8.4 Easily Import and Export Your Structured Data 153 8.5 Store the Output of a Command in a CSV File 155 8.6 Import Structured Data from a CSV File 156 8.7 Use Excel to Manage Command Output 157 9. Internet-Enabled Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 9.0 Introduction 160 9.1 Download a File from the Internet 160 9.2 Download a Web Page from the Internet 161 9.3 Program: Get-PageUrls 163 9.4 Program: Connect-WebService 166 9.5 Export Command Output As a Web Page 170 9.6 Program: Send an Email 170 9.7 Program: Interact with Internet Protocols 172 10. Code Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 10.0 Introduction 176 10.1 Write a Script 176 10.2 Write a Function 179 10.3 Write a Script Block 180 10.4 Return Data from a Script, Function, or Script Block 182 10.5 Place Common Functions in a Library 184 10.6 Access Arguments of a Script, Function, or Script Block 185 www.it-ebooks.info Table of Contents | ix 10.7 Access Pipeline Input 188 10.8 Write Pipeline-Oriented Scripts with Cmdlet Keywords 189 10.9 Write a Pipeline-Oriented Function 193 11. Lists, Arrays, and Hashtables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 11.0 Introduction 195 11.1 Create an Array or List of Items 195 11.2 Create a Jagged or Multidimensional Array 197 11.3 Access Elements of an Array 198 11.4 Visit Each Element of an Array 199 11.5 Sort an Array or List of Items 200 11.6 Determine Whether an Array Contains an Item 200 11.7 Combine Two Arrays 201 11.8 Find Items in an Array That Match a Value 202 11.9 Remove Elements from an Array 203 11.10 Find Items in an Array Greater or Less Than a Value 204 11.11 Use the ArrayList Class for Advanced Array Tasks 205 11.12 Create a Hashtable or Associative Array 206 11.13 Sort a Hashtable by Key or Value 207 12. User Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 12.0 Introduction 209 12.1 Read a Line of User Input 209 12.2 Read a Key of User Input 210 12.3 Program: Display a Menu to the User 211 12.4 Display Messages and Output to the User 213 12.5 Provide Progress Updates on Long-Running Tasks 216 12.6 Write Culture-Aware Scripts 217 12.7 Program: Invoke a Script Block with Alternate Culture Settings 220 12.8 Access Features of the Host’s User Interface 221 12.9 Program: Add a Graphical User Interface to Your Script 223 13. Tracing and Error Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13.0 Introduction 226 13.1 View the Errors Generated by a Command 226 13.2 Handle Warnings, Errors, and Terminating Errors 228 13.3 Output Warnings, Errors, and Terminating Errors 230 13.4 Debug a Script 231 13.5 Collect Detailed Traces of a Script or Command 234 13.6 Program: Analyze a Script’s Performance Profile 234 www.it-ebooks.info [...]... started in PowerShell is a simple matter of launching PowerShell. exe rather than cmd.exe—the shells begin to diverge as you explore the intermediate and advanced functionality, but you can be productive in PowerShell immediately To launch Windows PowerShell Click Start ➝ All Programs ➝ Windows PowerShell 1.0 ➝ Windows PowerShell or alternatively, Click Start ➝ Run, and then type PowerShell A PowerShell. .. syntax and PowerShell- focused examples Preface www.it-ebooks.info | xxiii What You Need to Use This Book The majority of this book requires only a working installation of Windows PowerShell If you do not yet have PowerShell installed, you may obtain it by following the download link at http://www.microsoft.com /PowerShell This link provides download instructions for PowerShell on Windows XP, Windows Server... PART I I A Guided Tour of Windows PowerShell www.it-ebooks.info Tour www.it-ebooks.info 0 TOUR A Guided Tour of Windows PowerShell 1 Introduction Windows PowerShell promises to revolutionize the world of system management and command-line shells From its object-based pipelines, to its administrator focus, to its enormous reach into other Microsoft management technologies, PowerShell drastically improves... about PowerShell: its features, its commands, and its scripting language—but you’ll most importantly solve problems How This Book Is Organized This book consists of five main sections: a guided tour of PowerShell, PowerShell fundamentals, common tasks, administrator tasks, and a detailed reference Part 1: Tour A Guided Tour of Windows PowerShell breezes through PowerShell at a high level It introduces PowerShell s... using PowerShell It covers: • The PowerShell language and environment • Regular expression syntax and PowerShell- focused examples • PowerShell s automatic and default variables • PowerShell s standard verbs • Administrator-friendly NET classes and their uses • Administrator-friendly WMI classes and their uses • Administrator-friendly COM objects and their uses • NET string formatting syntax and PowerShell- focused... really need is a scripting environment that includes the FCL as an enabler That’s exactly what Windows PowerShell does In fact, Windows PowerShell runs in the same environment as that library and, as a result, works seamlessly with it I read a lot of press about the object-pipelining capabilities of Windows PowerShell Those capabilities are very cool and represent an excellent advance in the glue department—an... from writing a script and consulting documentation Not so when working with objects in Windows PowerShell Type this at a Windows PowerShell prompt: $objShell = New-Object –com Shell.Application $objShell | Get-Member It does a scripter good, does it not? That Lee Guy Hopefully my rambling has convinced you that Windows PowerShell is a good thing and that it’s worth your time to learn it Now, why do I think... Perform Advanced WMI Tasks Convert a VBScript WMI Script to PowerShell Automate Programs Using COM Scripting Interfaces Program: Query a SQL Data Source Access Windows Performance Counters Program: Invoke Native Windows API Calls Program: Add Inline C# to Your PowerShell Script Access a NET SDK Library Create Your Own PowerShell Cmdlet Add PowerShell Scripting to Your Own Program 255 255 257 258 261... T-1 4 | A Guided Tour of Windows PowerShell www.it-ebooks.info Figure T-1 Windows PowerShell, ready for input Example T-1 Entering many standard DOS and UNIX-style file manipulation commands produces the same results you get when you use them with any other Windows shell PS PS PS PS C:\Documents and Settings\Lee> function Prompt { "PS >" } >pushd >cd \ >dir Directory: Microsoft .PowerShell. Core\FileSystem::C:\... Paths Program: Search the Windows Start Menu Get the Current Location Safely Build File Paths Out of Their Components Interact with PowerShell s Global Environment 240 240 242 244 246 247 248 250 252 253 254 15 Extend the Reach of Windows PowerShell 255 15.0 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 15.12 15.13 Introduction Access Windows Management Instrumentation . www.it-ebooks.info Windows PowerShell Cookbook ™ www.it-ebooks.info Other Microsoft .NET resources from O’Reilly Related titles Windows PowerShell Quick Reference Windows. free. www.it-ebooks.info Windows PowerShell Cookbook ™ Lee Holmes Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo www.it-ebooks.info Windows PowerShell