www.it-ebooks.info www.it-ebooks.info Lee Holmes THIRD EDITION Windows PowerShell Cookbook www.it-ebooks.info ISBN: 978-1-449-32068-3 [LSI] Windows PowerShell Cookbook, Third Edition by Lee Holmes Copyright © 2013 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 corporate@oreilly.com. Editor: Rachel Roumeliotis Production Editor: Kara Ebrahim Proofreader: Rachel Monaghan Indexer: Angela Howard Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest October 2007: First Edition August 2010: Second Edition January 2013: Third Edition Revision History for the First Edition: 2012-12-21 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449320683 for release details. 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 tortoise, 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 trade‐ mark 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. www.it-ebooks.info Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix Part I. Tour A Guided Tour of Windows PowerShell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii Part II. Fundamentals 1. The Windows PowerShell Interactive Shell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.1. Run Programs, Scripts, and Existing Tools 19 1.2. Run a PowerShell Command 23 1.3. Resolve Errors Calling Native Executables 24 1.4. Supply Default Values for Parameters 26 1.5. Invoke a Long-Running or Background Command 28 1.6. Program: Monitor a Command for Changes 32 1.7. Notify Yourself of Job Completion 35 1.8. Customize Your Shell, Profile, and Prompt 36 1.9. Customize PowerShell’s User Input Behavior 39 1.10. Customize PowerShell’s Command Resolution Behavior 40 1.11. Find a Command to Accomplish a Task 43 1.12. Get Help on a Command 45 1.13. Update System Help Content 47 1.14. Program: Search Help for Text 49 1.15. Launch PowerShell at a Specific Location 50 1.16. Invoke a PowerShell Command or Script from Outside PowerShell 52 1.17. Understand and Customize PowerShell’s Tab Completion 55 1.18. Program: Learn Aliases for Common Commands 59 1.19. Program: Learn Aliases for Common Parameters 61 iii www.it-ebooks.info 1.20. Access and Manage Your Console History 64 1.21. Program: Create Scripts from Your Session History 66 1.22. Invoke a Command from Your Session History 68 1.23. Program: Search Formatted Output for a Pattern 69 1.24. Interactively View and Process Command Output 70 1.25. Program: Interactively View and Explore Objects 72 1.26. Store the Output of a Command into a File 79 1.27. Add Information to the End of a File 80 1.28. Record a Transcript of Your Shell Session 81 1.29. Extend Your Shell with Additional Commands 82 1.30. Use Commands from Customized Shells 84 1.31. Save State Between Sessions 85 2. Pipelines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 2.1. Filter Items in a List or Command Output 90 2.2. Group and Pivot Data by Name 91 2.3. Program: Simplify Most Where-Object Filters 94 2.4. Program: Interactively Filter Lists of Objects 96 2.5. Work with Each Item in a List or Command Output 99 2.6. Automate Data-Intensive Tasks 101 2.7. Program: Simplify Most Foreach-Object Pipelines 105 2.8. Intercept Stages of the Pipeline 108 2.9. Automatically Capture Pipeline Output 109 2.10. Capture and Redirect Binary Process Output 111 3. Variables and Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 3.1. Display the Properties of an Item as a List 118 3.2. Display the Properties of an Item as a Table 120 3.3. Store Information in Variables 122 3.4. Access Environment Variables 123 3.5. Program: Retain Changes to Environment Variables Set by a Batch File 126 3.6. Control Access and Scope of Variables and Other Items 128 3.7. Program: Create a Dynamic Variable 130 3.8. Work with .NET Objects 133 3.9. Create an Instance of a .NET Object 138 3.10. Create Instances of Generic Objects 140 3.11. Reduce Typing for Long Class Names 141 3.12. Use a COM Object 143 3.13. Learn About Types and Objects 143 3.14. Get Detailed Documentation About Types and Objects 145 3.15. Add Custom Methods and Properties to Objects 147 3.16. Create and Initialize Custom Objects 150 iv | Table of Contents www.it-ebooks.info 3.17. Add Custom Methods and Properties to Types 154 3.18. Define Custom Formatting for a Type 158 4. Looping and Flow Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 4.1. Make Decisions with Comparison and Logical Operators 163 4.2. Adjust Script Flow Using Conditional Statements 165 4.3. Manage Large Conditional Statements with Switches 167 4.4. Repeat Operations with Loops 170 4.5. Add a Pause or Delay 172 5. Strings and Unstructured Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 5.1. Create a String 175 5.2. Create a Multiline or Formatted String 177 5.3. Place Special Characters in a String 178 5.4. Insert Dynamic Information in a String 179 5.5. Prevent a String from Including Dynamic Information 180 5.6. Place Formatted Information in a String 181 5.7. Search a String for Text or a Pattern 183 5.8. Replace Text in a String 185 5.9. Split a String on Text or a Pattern 187 5.10. Combine Strings into a Larger String 190 5.11. Convert a String to Uppercase or Lowercase 191 5.12. Trim a String 193 5.13. Format a Date for Output 194 5.14. Program: Convert Text Streams to Objects 196 5.15. Generate Large Reports and Text Streams 200 5.16. Generate Source Code and Other Repetitive Text 202 6. Calculations and Math. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 6.1. Perform Simple Arithmetic 207 6.2. Perform Complex Arithmetic 209 6.3. Measure Statistical Properties of a List 213 6.4. Work with Numbers as Binary 214 6.5. Simplify Math with Administrative Constants 218 6.6. Convert Numbers Between Bases 219 7. Lists, Arrays, and Hashtables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 7.1. Create an Array or List of Items 223 7.2. Create a Jagged or Multidimensional Array 225 7.3. Access Elements of an Array 226 7.4. Visit Each Element of an Array 228 7.5. Sort an Array or List of Items 229 Table of Contents | v www.it-ebooks.info 7.6. Determine Whether an Array Contains an Item 230 7.7. Combine Two Arrays 231 7.8. Find Items in an Array That Match a Value 232 7.9. Compare Two Lists 233 7.10. Remove Elements from an Array 234 7.11. Find Items in an Array Greater or Less Than a Value 235 7.12. Use the ArrayList Class for Advanced Array Tasks 236 7.13. Create a Hashtable or Associative Array 238 7.14. Sort a Hashtable by Key or Value 239 8. Utility Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 8.1. Get the System Date and Time 243 8.2. Measure the Duration of a Command 244 8.3. Read and Write from the Windows Clipboard 246 8.4. Generate a Random Number or Object 248 8.5. Program: Search the Windows Start Menu 250 8.6. Program: Show Colorized Script Content 251 Part III. Common Tasks 9. Simple Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 9.1. Get the Content of a File 259 9.2. Search a File for Text or a Pattern 261 9.3. Parse and Manage Text-Based Logfiles 264 9.4. Parse and Manage Binary Files 267 9.5. Create a Temporary File 270 9.6. Search and Replace Text in a File 271 9.7. Program: Get the Encoding of a File 275 9.8. Program: View the Hexadecimal Representation of Content 277 10. Structured Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 10.1. Access Information in an XML File 281 10.2. Perform an XPath Query Against XML 284 10.3. Convert Objects to XML 286 10.4. Modify Data in an XML File 287 10.5. Easily Import and Export Your Structured Data 289 10.6. Store the Output of a Command in a CSV or Delimited File 291 10.7. Import CSV and Delimited Data from a File 292 10.8. Manage JSON Data Streams 294 10.9. Use Excel to Manage Command Output 295 vi | Table of Contents www.it-ebooks.info 10.10. Parse and Interpret PowerShell Scripts 297 11. Code Reuse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 11.1. Write a Script 303 11.2. Write a Function 306 11.3. Find a Verb Appropriate for a Command Name 308 11.4. Write a Script Block 309 11.5. Return Data from a Script, Function, or Script Block 311 11.6. Package Common Commands in a Module 314 11.7. Write Commands That Maintain State 317 11.8. Selectively Export Commands from a Module 320 11.9. Diagnose and Interact with Internal Module State 322 11.10. Handle Cleanup Tasks When a Module Is Removed 324 11.11. Access Arguments of a Script, Function, or Script Block 325 11.12. Add Validation to Parameters 330 11.13. Accept Script Block Parameters with Local Variables 334 11.14. Dynamically Compose Command Parameters 336 11.15. Provide -WhatIf, -Confirm, and Other Cmdlet Features 338 11.16. Add Help to Scripts or Functions 340 11.17. Add Custom Tags to a Function or Script Block 343 11.18. Access Pipeline Input 345 11.19. Write Pipeline-Oriented Scripts with Cmdlet Keywords 347 11.20. Write a Pipeline-Oriented Function 351 11.21. Organize Scripts for Improved Readability 352 11.22. Invoke Dynamically Named Commands 354 11.23. Program: Enhance or Extend an Existing Cmdlet 356 12. Internet-Enabled Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 12.1. Download a File from an FTP or Internet Site 365 12.2. Upload a File to an FTP Site 366 12.3. Download a Web Page from the Internet 368 12.4. Parse and Analyze a Web Page from the Internet 373 12.5. Script a Web Application Session 375 12.6. Program: Get-PageUrls 379 12.7. Interact with REST-Based Web APIs 383 12.8. Connect to a Web Service 385 12.9. Export Command Output as a Web Page 387 12.10. Send an Email 388 12.11. Program: Monitor Website Uptimes 389 12.12. Program: Interact with Internet Protocols 391 13. User Interaction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Table of Contents | vii www.it-ebooks.info 13.1. Read a Line of User Input 397 13.2. Read a Key of User Input 398 13.3. Program: Display a Menu to the User 399 13.4. Display Messages and Output to the User 401 13.5. Provide Progress Updates on Long-Running Tasks 404 13.6. Write Culture-Aware Scripts 405 13.7. Support Other Languages in Script Output 409 13.8. Program: Invoke a Script Block with Alternate Culture Settings 412 13.9. Access Features of the Host’s User Interface 414 13.10. Program: Add a Graphical User Interface to Your Script 415 13.11. Interact with MTA Objects 418 14. Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 14.1. Prevent Common Scripting Errors 422 14.2. Trace Script Execution 424 14.3. Set a Script Breakpoint 428 14.4. Debug a Script When It Encounters an Error 430 14.5. Create a Conditional Breakpoint 432 14.6. Investigate System State While Debugging 434 14.7. Program: Watch an Expression for Changes 437 14.8. Program: Get Script Code Coverage 440 15. Tracing and Error Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 15.1. Determine the Status of the Last Command 443 15.2. View the Errors Generated by a Command 445 15.3. Manage the Error Output of Commands 447 15.4. Program: Resolve an Error 448 15.5. Configure Debug, Verbose, and Progress Output 450 15.6. Handle Warnings, Errors, and Terminating Errors 452 15.7. Output Warnings, Errors, and Terminating Errors 455 15.8. Program: Analyze a Script’s Performance Profile 456 16. Environmental Awareness. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 16.1. View and Modify Environment Variables 463 16.2. Modify the User or System Path 465 16.3. Access Information About Your Command’s Invocation 466 16.4. Program: Investigate the InvocationInfo Variable 468 16.5. Find Your Script’s Name 471 16.6. Find Your Script’s Location 472 16.7. Find the Location of Common System Paths 473 16.8. Get the Current Location 476 16.9. Safely Build File Paths Out of Their Components 477 viii | Table of Contents www.it-ebooks.info [...]... working installation of Windows PowerShell Windows 7, Windows 8, Windows Server 2008 R2, and Windows Server 2012 include Windows PowerShell by default If you do not yet have PowerShell installed, you may obtain it by following the download link here This link provides download instructions for PowerShell on Windows XP, Windows Server 2003, and Windows Vista For Windows Server 2008, PowerShell comes installed... productive in PowerShell immediately To launch Windows PowerShell, do one of the following: • Click Start→All Programs→Accessories Windows PowerShell • Click Start→Run, and then type PowerShell A PowerShell prompt window opens that’s nearly identical to the traditional command prompt window of Windows XP, Windows Server 2003, and their many ancestors The PS C:\Users\Lee> prompt indicates that PowerShell. .. first two editions of this great book You may even be asking yourself why you need a third edition of the same book, and I will tell you: this is not the same book It is a completely revised book that takes advantage of the significant changes we have made to both Windows PowerShell 3.0 and to the underlying operating system Consider this: Windows PowerShell 1.0 had 129 cmdlets, but Windows PowerShell. .. solve problems How This Book Is Organized This book consists of five main sections: a guided tour of PowerShell, PowerShell fun‐ damentals, common tasks, administrator tasks, and a detailed reference Part I: Tour A Guided Tour of Windows PowerShell breezes through PowerShell at a high level It introduces PowerShell s core features: • An interactive shell • A new command model • An object-based pipeline...16.10 Interact with PowerShell s Global Environment 16.11 Determine PowerShell Version Information 16.12 Test for Administrative Privileges 478 479 480 17 Extend the Reach of Windows PowerShell 483 17.1 Automate Programs Using COM Scripting Interfaces 17.2 Program: Query a SQL Data Source 17.3 Access Windows Performance Counters 17.4 Access Windows API Functions... anything PowerShell has to offer • PowerShell enables ubiquitous scripting With a fully fledged scripting language that works directly from the command line, PowerShell lets you automate tasks with ease • PowerShell bridges many technologies By letting you work with NET, COM, WMI, XML, and Active Directory, PowerShell makes working with these previously iso‐ lated technologies easier than ever before • PowerShell. .. stores Through its provider model, PowerShell lets you manage data stores using the same techniques you already use to manage files and folders We’ll explore each of these pillars in this introductory tour of PowerShell If you are running Windows 7 (or later) or Windows 2008 R2 (or later), PowerShell is already installed If not, visit the download link here to install it PowerShell and its supporting technologies... Cookbook is also a textbook of how to write great Windows PowerShell scripts Just as a budding saxophonist benefits from watching a legend such as Charlie Parker ply his ax, so too does a budding scripter benefit from watching one of the guys who literally wrote Windows PowerShell write scripts Each of these recipes is a perfectly crafted example of a Windows PowerShell script—your task is to study these... indicates that PowerShell is ready for input, as shown in Figure I-1 4 | A Guided Tour of Windows PowerShell www.it-ebooks.info Figure I-1 Windows PowerShell, ready for input Once you’ve launched your PowerShell prompt, you can enter DOS-style and Unix-style commands to navigate around the filesystem just as you would with any Windows or Unix command prompt—as in the interactive session shown in Example I-1... www.it-ebooks.info PART I Tour www.it-ebooks.info www.it-ebooks.info A Guided Tour of Windows PowerShell 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 the productivity of administrators and . www.it-ebooks.info www.it-ebooks.info Lee Holmes THIRD EDITION Windows PowerShell Cookbook www.it-ebooks.info ISBN: 978-1-449-32068-3 [LSI] Windows PowerShell Cookbook, Third Edition by Lee Holmes Copyright. both Windows PowerShell 3.0 and to the underlying operating system. Consider this: Windows PowerShell 1.0 had 129 cmdlets, but Windows PowerShell 3.0 on Windows