By Steve Seguis - It-docs

Transcription

Windows PowerShell 2FORDUMmIES‰by Steve Seguis

Windows PowerShell 2 For Dummies Published byWiley Publishing, Inc.111 River StreetHoboken, NJ 07030-5774www.wiley.comCopyright 2009 by Wiley Publishing, Inc., Indianapolis, IndianaPublished by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaNo part of this publication may be reproduced, stored in a retrieval system or transmitted in any form orby any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior writtenpermission of the Publisher, or authorization through payment of the appropriate per-copy fee to theCopyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley& Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for theRest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making EverythingEasier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission.Windows PowerShell is a trademark of Microsoft Corporation in the United States and/or other countries.All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associatedwith any product or vendor mentioned in this book.LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OFTHE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BECREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIESCONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THEUNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OROTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OFA COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THEAUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCEOF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSESTHE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS ITMAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THISWORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN ANDWHEN IT IS READ.For general information on our other products and services, please contact our Customer CareDepartment within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.For technical support, please visit www.wiley.com/techsupport.Wiley also publishes its books in a variety of electronic formats. Some content that appears in print maynot be available in electronic books.Library of Congress Control Number: 2009931743ISBN: 978-0-470-37198-5Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1

About the AuthorSteve Seguis lives with his amazing wife, Annalene, in New York City, NewYork. He is a twelve-year Windows Systems Engineer veteran and specializesin systems automation. He was a Microsoft Most Valuable Professional (MVP)for Windows Server — Admin Framework from 2004–2007. He is also a contributing writer and technical editor for Windows IT Pro and, most recently,has published a book on Windows Server 2008 Administration.DedicationTo my parents, Romeo and Lourdes, who gave me the opportunities thathave allowed me to pursue my dreams and become who I am today.

Author’s AcknowledgmentsI’ve always been a fan of the For Dummies books, which has often resultedin one or two chuckles from my colleagues due to the incorrect perceptionthat somehow reading a For Dummies book implies a lack of intelligence.The reality is that I’m a fan of making complex things simple and I like booksthat focus on getting me the information I need in an easy, digestible format.The For Dummies books have been doing this for years, and ever since I readmy first For Dummies book (specifically C For Dummies by Dan Gookin, overa dozen years ago), I was captured by the ease at which I was able to gainknowledge while having the occasional laugh. I never in my wildest imagination thought I’d ever have the opportunity to write one myself . . . that is untilmy agent, David Fugate, got me in touch with the good people over at WileyPublishing and got this journey started. Thanks David!I’d like to thank Greg Croy, Executive Editor, for getting my proposal for thisbook approved. He actually retired before I was done writing the book, butkudos to him for getting the ball rolling. Thanks goes out to Blair Pottenger,Project Editor, for keeping me well-informed, answering all my questions,and putting in a lot of work to get the book finished. Of course, I’d also like tothank Katie Mohr, Acquisitions Editor, who took over Greg’s role in this project after he retired. Katie went on maternity leave just before we got donewith the book, so congratulations Katie on the new baby. The project had hita bit of a plateau half way through, but when she took over we were able toregroup and get everything back on track.I have to thank my very patient and supportive wife, Annalene, who puts upwith me disappearing into the cubby hole I call my home office for late nightwriting sessions and generally dealing with all my quirks. We somehow worktogether to stay sane despite our lives going at 100 miles an hour.I also have to thank my parents and my family for understanding how busyI get, generally staying out of my hair (what hair I have left), and letting mepursue my interests even though they continue to say that I need to slowdown a bit and get some more sleep.Finally, I’d like to thank the guys over at Microsoft for creating this awesomescripting language called Windows PowerShell. We’ve come a long way sincebatch files and as a long-time Windows administrator, I bow to your greatness. Windows PowerShell is truly empowering and more Windows folks inevery company need to embrace it.

Publisher’s AcknowledgmentsWe’re proud of this book; please send us your comments through our online registration form locatedat http://dummies.custhelp.com. For other comments, please contact our Customer CareDepartment within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.Some of the people who helped bring this book to market include the following:Acquisition, Editorial, and MediaDevelopmentComposition ServicesProject Editor: Blair J. PottengerExecutive Editor: Greg CroyAcquisitions Editor: Katie MohrProject Coordinator: Lynsey StanfordLayout and Graphics: Melanee Habig,Melissa K. JesterCopy Editors: Virginia Sanders, Kathy SimpsonProofreaders: Melissa Cossell,Christopher M. JonesTechnical Editor: David DalanIndexer: Potomac Indexing, LLCEditorial Manager: Kevin KirschnerMedia Development Project Manager:Laura Moss-HollisterMedia Development Assistant ProjectManager: Jenny SwisherMedia Development Associate Producer:Josh FrankSr. Editorial Assistant: Cherie CaseCartoons: Rich Tennant (www.the5thwave.com)Publishing and Editorial for Technology DummiesRichard Swadley, Vice President and Executive Group PublisherAndy Cummings, Vice President and PublisherMary Bednarek, Executive Acquisitions DirectorMary C. Corder, Editorial DirectorPublishing for Consumer DummiesDiane Graves Steele, Vice President and PublisherComposition ServicesDebbie Stailey, Director of Composition Services

Contents at a GlanceIntroduction . 1Part I: Get ting a Bird’s-Eye View of PowerShell 2 . 9Chapter 1: The Windows PowerShell Rap Sheet. 11Chapter 2: Customizing and Shortcutting the Environment . 21Chapter 3: A Pinch of Shell, a Pound of Power . 37Part II: PowerShell’s Basic Structure and Syntax. 47Chapter 4: Shelling Out Commands and Scripts . 49Chapter 5: When Dollars Turn into Variables . 61Chapter 6: A Bit of Logic to Save the Day . 77Chapter 7: Working on a Pipeline . 89Part III: Complex Data Description and Sharing . 97Chapter 8: Working with Windows Management Instrumentation . 99Chapter 9: Bringing Strings into the Limelight . 117Chapter 10: I’ll Take Numbers for 100, Please. 137Chapter 11: Grouping Data Using Arrays and Hash Tables . 147Chapter 12: Readin’ and Writin’ Files . 159Chapter 13: Going On a Date with PowerShell . 175Part IV: Controlling Where and HowYou Operate PowerShell . 185Chapter 14: Using Functions to Divide and Conquer . 187Chapter 15: PowerShell Ninjas: Running Jobs Remotely or in the Background . 209Chapter 16: Making Your Script Speak Different Languages . 223Chapter 17: Smashing Those Bugs . 231Part V: Real-World Windows AdministrationUsing PowerShell . 245Chapter 18: Mission Control: All Systems Go . 247Chapter 19: Taming the Windows Registry . 261Chapter 20: Reaching Out to Active Directory . 273Chapter 21: PowerShell Lockdown . 287Chapter 22: Converting Your Old Scripts: Out with the Old, In with the New . 301

Part VI: Configuring and Reporting Via PowerShell . 317Chapter 23: Controlling Your Network Configuration. 319Chapter 24: Managing Your Hardware . 331Chapter 25: Making Reporting Easy . 345Part VII: The Par t of Tens . 357Chapter 26: The Ten Most Important Cmdlets . 359Chapter 27: Ten Common PowerShell Mistakes . 365Bonus Chapter 1: Handling Exceptions. 1Index . 375

Table of ContentsIntroduction . 1About This Book . 1Conventions Used in This Book . 2What You’re Not to Read . 3Foolish Assumptions . 3How This Book Is Organized . 4Part I: Getting a Bird’s Eye View of PowerShell 2. 4Part II: PowerShell’s Basic Structure and Syntax . 4Part III: Complex Data Description and Sharing. 5Part IV: Controlling Where and How You Operate PowerShell. 5Part V: Real-World Windows Administration Using PowerShell . 6Part VI: Configuring and Reporting Via PowerShell. 6Part VII: The Part of Tens . 6Icons Used in This Book . 7What’s on the Web Site . 7Where to Go from Here . 7Part I: Get ting a Bird’s-Eye View of PowerShell 2 . 9Chapter 1: The Windows PowerShell Rap Sheet. . . . . . . . . . . . . . . . . .11Addressing the Need for a Powerful, Windows-FocusedScripting Language . 12Watching Monad morph into PowerShell . 12A little bit on Windows PowerShell 1.0 . 13Windows PowerShell 2, the Next Evolution . 14Installing Windows PowerShell 2 . 15Firing up the Windows PowerShell Command Shell . 16Going GUI: The Windows PowerShell Integrated ShellEnvironment (ISE) . 18Chapter 2: Customizing and Shortcutting the Environment . . . . . . . . .21Personalizing the Look and Feel of the Command Shell. 22Adding color to your world . 22Getting size-specific with your windows . 22A window by any other name . . . . 24Changing Your PowerShell Profile. 24Making the Windows PowerShell ISE Work for You . 27Customizing the ISE . 28Adding your own functions to the ISE menu . 28Creating Aliases . 30

xWindows PowerShell 2 For DummiesDeleting Aliases. 31Accessing the Alias Drive . 32Creating Persistent Aliases. 33Getting to Know Tab Expansion . 34Chapter 3: A Pinch of Shell, a Pound of Power. . . . . . . . . . . . . . . . . . . .37Getting a Taste of Windows PowerShell . 38Creating Your First Script . 39Breaking Down Your First Script . 41Sneaking a Peek at Complex Scripts. 43Examining the Nuts and Bolts of the Complist Script . 45Part II: PowerShell’s Basic Structure and Syntax . 47Chapter 4: Shelling Out Commands and Scripts. . . . . . . . . . . . . . . . . . .49Cmdlets: The Little Commands That Could! . 49Putting Cmdlets under a microscope . 50Checking out existing Cmdlets . 51Making Cmdlets understand you . 53One Shell to Rule Them All . 55Windows Shell scripts . 55Windows Scripting Host . 59Chapter 5: When Dollars Turn into Variables . . . . . . . . . . . . . . . . . . . . .61Discovering Variables: They Vary Very Much . 62Getting to Know Data Types . 62Dealing with data types . 64Explicitly defining the data type . 65Casting values . 67Constant and Read-Only Variables. 70Understanding Automatic Variables . 71Working with Objects through Variables . 74Chapter 6: A Bit of Logic to Save the Day . . . . . . . . . . . . . . . . . . . . . . . .77A Logic Primer . 77Branching Using If/Else . 80Using the Switch Statement. 83Doing It Over and Over and Over Again with Loops . 83Looping with For . 84Using Foreach to loop through collections . 85Looping for a While . 86Running a loop at least once with Do While . 86Taking a look at Do Until . 87Avoiding loop pitfalls . 88

Table of ContentsChapter 7: Working on a Pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89Using Pipelines to Streamline Your Commands . 90Stringing Commands Together . 91Getting the Right Output . 94Part III: Complex Data Description and Sharing . 97Chapter 8: Working with Windows ManagementInstrumentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .99Getting Familiar with Windows Management Instrumentation . 100Examining the WMI architecture . 100Poking around in WMI namespaces . 101Securing WMI. 103Making Windows PowerShell Interact with WMI . 103Using SQL Syntax in WMI to Get WQL. 106Harnessing the Power of WMI . 108Querying service status . 108Looking for event log entries. 109Changing WMI Authentication Levels . 109Pretending to Be Someone Else Using Impersonation . 111Using the New WMI Cmdlets . 112Making things happen with Invoke-WMIMethod . 113Deleting objects using Remove-WmiObject . 114Setting WMI properties using Set-WmiInstance . 114Chapter 9: Bringing Strings into the Limelight . . . . . . . . . . . . . . . . . . .117Taking Your First Look at Strings . 117Differentiating between empty and null strings. 118Creating literal strings . 118Simplifying using Here-Strings . 119Performing String Surgery . 120Combining strings . 120Combining strings with nonstrings . 121Splitting strings . 122Snipping off a piece of a string . 123Performing string substitutions . 125Working with String Positions . 125Changing the Case of Strings. 127Using Regular Expressions . 127Creating the simplest RegEx using literal characters . 128Performing more dynamic searches using character sets . 130Using modifiers to define optional or repeating sequences. 132Using anchors to maintain position . 134Coming up with alternatives . 135Making use of RegEx in Windows PowerShell . 136xi

xiiWindows PowerShell 2 For DummiesChapter 10: I’ll Take Numbers for 100, Please . . . . . . . . . . . . . . . . . .137Putting Numeric Data Types under a Microscope . 137Having a look at integral data types . 138Getting precise using nonintegral data types . 139Doing Some Calculations . 139Adding things up . 140Reducing values with subtraction . 142Expanding through multiplication . 143Reducing through division . 143Rounding Off Values . 144Creating Random Numbers . 145Converting Numbers . 145Watching Out for Overflow. 146Chapter 11: Grouping Data Using Arrays and Hash Tables . . . . . . . .147Taking an In-Depth Look at Arrays . 148Creating and Using Arrays. 148Accessing array elements . 149Looping through arrays . 150Growing Arrays Dynamically . 151Creating Multidimensional Arrays . 152Finding Other Uses for Arrays . 153Working with Hash Tables: The Array’s Useful Cousin . 155Creating and using hash tables . 155Modifying hash tables . 157Looping through hash tables . 158Chapter 12: Readin’ and Writin’ Files . . . . . . . . . . . . . . . . . . . . . . . . . . .159Having Some Fun with the File System . 159Moving around the file system . 160Managing directories . 160Manipulating files in the file system . 162Reading Text Files . 163Writing Files . 164Working with XML . 166Reading and writing XML files . 168Saving objects in XML files . 169Working with HTML . 171Chapter 13: Going On a Date with PowerShell. . . . . . . . . . . . . . . . . . .175Going On Your First Date. 175Getting the date and time in a specific format . 176Creating your own dates . 178Using Date Math (It’s Not Just for Nerds) . 179Calculating time differences . 179Looking into the future. 180Checking whether it’s daylight saving time. 181

Table of ContentsDealing with Time Zones . 182Standardizing with Coordinated Universal Time . 182Using the TimeZone class . 183Part IV: Controlling Where and How You OperatePowerShell . 185Chapter 14: Using Functions to Divide and Conquer . . . . . . . . . . . . . .187Reusing Code Using Functions. 187Creating your first function . 188Defining parameters . 189Returning values . 191Using Scope . 193Understanding scope rules . 193Watching out for name overlap . 195Defining functions in Global scope . 197Creating Your Own Cmdlets — Advanced Functions! . 197Understanding the structure of Advanced Functions . 198Defining attributes . 199Defining parameters . 200Using methods. 204Running Advanced Functions. 204Finding uses for Advanced Functions . 207Chapter 15: PowerShell Ninjas: Running Jobs Remotely orin the Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .209Using Background Jobs. 210Enabling WinRM . 210Starting a new job . 210Getting results . 211Waiting for a job . 213Terminating a job . 214Bringing a job to a grinding halt . 214Running Commands Remotely . 215Using Windows PowerShell everywhere. 215Getting what you need for remote commands. 216Speaking PowerShell with a different computer . 216Invoking commands remotely . 217Creating a persistent connection.

Author’s Acknowledgments I’ve always been a fan of the For Dummies books, which has often resulted in one or two chuckles from my colleagues due to the incorrect perception that somehow reading a For Dummies book implies a lack of intelligence. The reality is that I