30
Professional Windows PowerShell Programming Snap-ins, Cmdlets, Hosts, and Providers Arul Kumaravel Jon White Michael Naixin Li Scott Happell Guohui Xie Krishna C. Vutukuri Wiley Publishing, Inc.

Professional Windows PowerShell Programming...Library of Congress Cataloging-in-Publication Data. No part of this publication may be reproduced, stored in a retrieval system or transmitted

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

  • Kumaravel ffirs.tex V1 - 01/09/2008 8:43pm Page iii

    ProfessionalWindows PowerShell

    Programming

    Snap-ins,Cmdlets,Hosts,andProviders

    Arul KumaravelJon White

    Michael Naixin LiScott HappellGuohui Xie

    Krishna C. Vutukuri

    Wiley Publishing, Inc.

    File AttachmentC1.jpg

  • Kumaravel ffirs.tex V1 - 01/09/2008 8:43pm Page ii

  • Kumaravel ffirs.tex V1 - 01/09/2008 8:43pm Page i

    ProfessionalWindows PowerShell

    Programming

    Preface xvii

    Introduction xix

    Chapter 1: Introduction to PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Chapter 2: Extending Windows PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Chapter 3: Understanding the Extended Type System . . . . . . . . . . . . . . . . . . . . . . 29Chapter 4: Developing Cmdlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Chapter 5: Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117Chapter 6: Hosting the PowerShell Engine in Applications . . . . . . . . . . . . . . . . . 165Chapter 7: Hosts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Chapter 8: Formatting&Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233Appendix A: Cmdlet Verb Naming Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257Appendix B: Cmdlet Parameter Naming Guidelines . . . . . . . . . . . . . . . . . . . . . . . . 263Appendix C: Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271Appendix D: Provider Base Classes and Overrides/Interfaces. . . . . . . . . . . . . . 283Appendix E: Core Cmdlets for Provider Interaction. . . . . . . . . . . . . . . . . . . . . . . . . 303

    Index 307

  • Kumaravel ffirs.tex V1 - 01/09/2008 8:43pm Page ii

  • Kumaravel ffirs.tex V1 - 01/09/2008 8:43pm Page iii

    ProfessionalWindows PowerShell

    Programming

    Snap-ins,Cmdlets,Hosts,andProviders

    Arul KumaravelJon White

    Michael Naixin LiScott HappellGuohui Xie

    Krishna C. Vutukuri

    Wiley Publishing, Inc.

  • Kumaravel ffirs.tex V1 - 01/09/2008 8:43pm Page iv

    Windows PowerShell Programming:Snap-ins, Cmdlets, Hosts, and ProvidersPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright 2008 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN: 978-0-470-17393-0

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    Library of Congress Cataloging-in-Publication Data

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, orauthorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should beaddressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

    Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warrantieswith respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties,including without limitation warranties of fitness for a particular purpose. No warranty may be created or extendedby sales or promotional materials. The advice and strategies contained herein may not be suitable for everysituation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting,or other professional services. If professional assistance is required, the services of a competent professional personshould be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that anorganization or Website is referred to in this work as a citation and/or a potential source of further informationdoes not mean that the author or the publisher endorses the information the organization or Website may provideor recommendations it may make. Further, readers should be aware that Internet Websites listed in this work mayhave changed or disappeared between when this work was written and when it is read.

    For general information on our other products and services please contact our Customer Care Department within theUnited States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

    Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dressare trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States andother countries, and may not be used without written permission. Windows PowerShell is a trademark of MicrosoftCorporation in the United States and/or other countries. All other trademarks are the property of their respectiveowners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not beavailable in electronic books.

    www.wiley.com

  • Kumaravel fauth.tex V2 - 01/07/2008 10:17pm Page v

    About the AuthorArul Kumaravel is currently the Development Manager of the Windows PowerShell team. He hasworked with this team since its early days and led the team in shipping of version 1 of the product,and is presently leading the development of next version of PowerShell. Fascinated by computers froman early age, when he first learned programming using BASIC, he went on to get his Master of Sciencedegree in Computer Science from both the College of Engineering, Madras, India, and the Universityof Iowa. As a Microsoft intern, he wrote the first JavaScript/VBScript debugger for Internet Explorer 3,and was impressed by the potential to make a difference in millions of people’s lives by working forMicrosoft. He has been working at Microsoft for the past 11 years in various groups, shipping multipleversions of products, including Internet Explorer, the Windows operating system, and Content Manage-ment Server, and has even dabbled with Software as a Service with small business online services. Morerecently, attracted by the business side of technology, Arul has taken on the arduous task of pursuing hisM.B.A. at the Wharton Business School. He can be reached at [email protected].

    Jon White is a software engineer who lives and works in the idyllic surroundings of Seattle’s easternsuburbs. An original member of the PowerShell team at Microsoft, his professional career started inthe Administrative Tools group in Windows Server. As a hobbyist, Jon learned programming in hisearly teens after his father bought an 8088-based PC clone at a second-hand shop. The PC came withMS-DOS 2.0, which featured debug.exe with a 16-bit disassembler, but no assembler. As a result, Jon’sfirst dive into programming was disassembling long tables of bytes to create a reverse-lookup dictionaryfor manually converting assembly programs into executable binary code. Coincidentally, later in life hefiled the bug which removed debug.exe from 64-bit Windows. As a member of the PowerShell team,he wrote the language’s first production script, when he converted the team’s test harness from Perl toPowerShell script in 2004. When he’s not working (or writing about work) he’s either sailing or playingwith fire in the backyard. You can contact him at [email protected].

    Michael Naixin Li is the Senior Test Lead working on the Windows PowerShell team and currentlyoversees the testing of Windows PowerShell 2.0. Before Windows PowerShell, Michael worked on vari-ous major projects at Microsoft, including the development of MSN 1.x and 2.x, quality management forthe COM Services component in Windows 2000, NetDocs Web Client Access, Web Services in Hailstorm,and Software Licensing Service in Windows Vista. Before joining Microsoft, Michael was an assistantprofessor at Shanghai University of Science and Technology (now called Shanghai University). He holdsa Ph.D. in Computer Science from Colorado State University.

    Scott Happell has been working as a software engineer and tester for 10 years. Three of those years havebeen on the Windows PowerShell team, which was what brought him to Microsoft from New Jersey,where he worked at an Internet startup that went belly-up. Scott recently left Microsoft to become arecording engineer/rock star and is trying to find cool ways to use PowerShell to help him create music.

    George Xie was a Senior Developer in the Windows PowerShell team for three years, mainly focusingin the area of snap-in model and scripting language. Recently George joined Windows Mobile organi-zation for the Mobile Device Management product. Before joining Microsoft, George worked for SiebelSystems Inc. for several years.

    Krishna Chythanya Vutukuri is a Software Developer working on the Windows PowerShell team. BeforeWindows PowerShell, Krishna worked on various projects at Microsoft, which included the developmentof Windows Presentation Foundation. Before joining Microsoft, Krishna held various product develop-ment positions at Hewlett-Packard India Software Operations and Wipro Technologies. He holds a M.Sc(Tech.) in Information Systems from Birla Institute of Technology and Science, Pilani, India.

  • Kumaravel fauth.tex V2 - 01/07/2008 10:17pm Page vi

  • Kumaravel fcredit.tex V1 - 01/07/2008 10:18pm Page vii

    CreditsExecutive EditorChris Webb

    Development EditorHoward Jones

    Technical EditorMarco Shaw

    Production EditorRachel McConlogue

    Copy EditorLuann Rouff

    Editorial ManagerMary Beth Wakefield

    Production ManagerTim Tate

    Vice President and Executive Group PublisherRichard Swadley

    Vice President and Executive PublisherJoseph B. Wikert

    Project Coordinator, CoverLynsey Osborn

  • Kumaravel fcredit.tex V1 - 01/07/2008 10:18pm Page viii

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page ix

    Contents

    Preface xviiIntroduction xix

    Chapter 1: Introduction to PowerShell 1

    Windows PowerShell Design Principles 1Preserve the Customer’s Existing Investment 2Provide a Powerful, Object-Oriented Shell 2Extensibility, Extensibility, Extensibility 2Tear Down the Barriers to Development 2

    A Quick Tour of Windows PowerShell 3Cmdlets 3

    High-Level Architecture of Windows PowerShell 9Host Application 9Windows PowerShell Engine 10Windows PowerShell Snap-ins 10

    Summary 11

    Chapter 2: Extending Windows PowerShell 13

    Types of PowerShell Snap-ins 13Creating a Standard PowerShell Snap-in 14

    Writing a PowerShell Snap-in 14Registering Your PowerShell Snap-in 17Listing Available PowerShell Snap-ins 19Loading a PowerShell Snap-in to a Running Shell 19Removing a PowerShell Snap-in from a Running Shell 20Unregistering a PowerShell Snap-in 20Registering a PowerShell Snap-in without Implementing a Snap-in Clas 21Saving Snap-in Configuration 22Starting PowerShell with a Saved Snap-in Configuration 22Using a Profile to Save a Snap-in Configuration 23

    Creating a Custom PowerShell Snap-in 23Writing a Custom PowerShell Snap-in 23Using a Custom PowerShell Snap-in 25

    Summary 27

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page x

    Contents

    Chapter 3: Understanding the Extended Type System 29

    PSObject 29Constructing a PSObject 30

    PSObject(Object) 31PSObject() 31PSObject.AsPSObject(someObject) 32

    ImmediateBaseObject and BaseObject 33Members 34

    PSMemberInfoCollection 35ReadOnlyPSMemberInfoCollection 36Base, Adapted, and Extended Members 37

    Types of Members 37Properties 38Methods 46Sets 51

    TypeNames 53Lookup Algorithm 54Distance Algorithm 54PSObject Intrinsic Members and MemberSets 55Errors and Exceptions 55

    Runtime Errors 55Initialization Errors 56

    Type Conversion 57Standard PS Language Conversion 57Custom Converters 58

    ToString Mechanism 60Type Configuration (TypeData) 60

    Well-Known Members 62Script Access 62

    Summary 62

    Chapter 4: Developing Cmdlets 63

    Getting Started 63Command-Line Parsing 65Command Discovery 65Parameter Binding 66Command Invocation 67

    Using Parameters 67Mandatory Parameters 67Positional Parameters 68

    x

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page xi

    Contents

    Parameter Sets 71Parameter Validation 78Parameter Transformation 80

    Processing Pipeline Input 84Pipeline Parameter Binding 87

    Generating Pipeline Output 91Reporting Errors 92

    ErrorRecord 93ErrorDetails 95Non-terminating Errors and Terminating Errors 97

    Supporting ShouldProcess 98Confirming Impact Level 100ShouldContinue() 101

    Working with the PowerShell Path 101Documenting Cmdlet Help 106Best Practices for Cmdlet Development 114

    Naming Conventions 114Interactions with the Host 115

    Summary 116

    Chapter 5: Providers 117

    Why Implement a Provider? 118Providers versus Cmdlets 118

    Essential Concepts 119Paths 119Drives 121Error Handling 121Capabilities 122

    Hello World Provider 123Built-in Providers 125

    Alias Provider 125Environment Provider 126FileSystem Provider 126Function Provider 126Registry Provider 127Variable Provider 128Certificate Provider 128

    Base Provider Types 128CmdletProvider 129DriveCmdletProvider 129ItemCmdletProvider 129

    xi

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page xii

    Contents

    ContainerCmdletProvider 131NavigationCmdletProvider 132

    Optional Provider Interfaces 132IContentCmdletProvider 132IPropertyCmdletProvider 133IDynamicPropertyCmdletProvider 134ISecurityDescriptorCmdletProvider 134

    CmdletProvider 134Methods and Properties on CmdletProvider 136DriveCmdletProvider 139ItemCmdletProvider 141ContainerCmdletProvider 147NavigationCmdletProvider 153

    Design Guidelines and Tips 162Summary 163

    Chapter 6: Hosting the PowerShell Engine in Applications 165

    Runspaces and Pipelines 165Getting Started 166Executing a Command Line 166

    Using RunspaceInvoke 166Using Runspace and Pipeline 168

    Using the Output of a Pipeline 170The Return Value of Invoke() 170Using PSObject Objects Returned from a Pipeline 170Handling Terminating Errors 171

    Input, Output, and Errors for Synchronous Pipelines 172Passing Input to Your Pipeline 172The Output Pipe in Synchronous Execution 173Retrieving Non-Terminating Errors from the Error Pipe 173The ErrorRecord Type 174

    Other Pipeline Tricks 174Nested Pipelines 174Reusing Pipelines 175Copying a Pipeline Between Runspaces 175

    Configuring Your Runspace 176Creating a Runspace with a Custom Configuration 176Adding and Removing Snap-Ins 177Creating RunspaceConfiguration from a Console File 177Creating RunspaceConfiguration from an Assembly 177Using SessionStateProxy to Set and Retrieve Variables 178Fine-Tuning RunspaceConfiguration 179

    xii

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page xiii

    Contents

    Running a Pipeline Asynchronously 181Calling InvokeAsync() 181Closing the Input Pipe 182Reading Output and Error from an Asynchronous Pipeline 182Monitoring a Pipeline’s StateChanged Event 185Reading Terminating Errors via PipelineStateInfo.Reason 186Stopping a Running Pipeline 187

    Asynchronous Runspace Operations 187The OpenAsync() Method 187Handling the Runspace’s StateChanged Event 188

    Constructing Pipelines Programmatically 189Creating an Empty Pipeline 189Creating a Command 189Merging Command Results 190Adding Command Parameters 191Adding Commands to the Pipeline 192

    Cmdlets as an API Layer for GUI Applications 193High-Level Architecture 193Keys to Successful GUI Integration 194Providing a Custom Host 194

    Summary 195

    Chapter 7: Hosts 197

    Host-Windows PowerShell Engine Interaction 197Built-In Cmdlets That Interact with the Host 199

    Write-Debug 199Write-Verbose 200Write-Warning 202Write-Progress 203Write-Host and Out-Host 203Read-Host 204

    Cmdlet and Host Interaction 204PSHost Class 207

    InstanceId 208Name 209Version 210CurrentCulture 210CurrentUICulture 210PrivateData 211EnterNestedPrompt 211ExitNestedPrompt 212

    xiii

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page xiv

    Contents

    Application Notification Methods 214SetShouldExit 214

    PSHostUserInterface Class 221WriteDebugLine 222WriteVerboseLine 223WriteWarningLine 223WriteProgress 223WriteErrorLine 224Write Methods 224Prompt Method 224PromptForCredential 226Read Methods 227

    PSHostRawUserInterface Class 227Summary 231

    Chapter 8: Formatting & Output 233

    The Four View Types 233Table: format-table 234List: format-list 234Custom: format-custom 235Wide: format-wide 235

    Formatting without#.format.ps1xml 236Format Configuration File Example 237Loading Your Format File(s) 238

    Update-formatdata 239Snap-ins 240RunspaceConfiguration API 240

    Anatomy of a Format Configuration File 240View 241Name 241ViewSelectedBy 241GroupBy 242

    TableControl 243TableHeaders 243TableRowEntries 244

    ListControl 244ListEntries 245

    Wide Control 246WideEntries 246

    Custom Control 246CustomEntries 248

    xiv

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page xv

    Contents

    Miscellaneous Configuration Entries 248Wrap 248AutoSize 248

    Scenarios 249Format Strings 249Formatting Deserialized Objects 250Class Inheritance 250Selection Sets 253Colors 253

    Summary 255

    Appendix A: Cmdlet Verb Naming Guidelines 257

    Common Verbs 257Data Verbs 259Communication Verbs 260Diagnostic Verbs 260Lifecycle Verbs 261Security Verbs 261

    Appendix B: Cmdlet Parameter Naming Guidelines 263

    Ubiquitous Parameters 263Activity Parameters 264Date/Time Parameters 266Format Parameters 266Property Parameters 267Quantity Parameters 268Resource Parameters 268Security Parameters 269

    Appendix C: Metadata 271

    CmdletAttribute 271Cmdlet Attribute Example 272

    ParameterAttribute 272ParameterAttribute Example 273

    AliasAttribute 273AliasAttribute Example 273

    Argument Validation Attributes 273ValidateSetAttribute 274ValidatePatternAttribute 274ValidateLengthAttribute 274

    xv

  • Kumaravel ftoc.tex V2 - 01/08/2008 12:04am Page xvi

    Contents

    ValidateCountAttribute 275ValidateRangeAttribute 275

    Allow and Disallow Attributes 276AllowNullAttribute 276AllowEmptyStringAttribute 276AllowEmptyCollectionAttribute 277ValidateNotNullAttribute 277ValidateNotNullOrEmptyAttribute 277CredentialAttribute 277

    Extending Parameter Metadata Attributes 278ValidateArgumentsAttribute 278ValidateEnumeratedArgumentsAttribute 279ArgumentTransformationAttribute 279

    Adding Attributes to Dynamic Parameters at Runtime 280ValidateScriptAttribute 281

    Appendix D: Provider Base Classes and Overrides/Interfaces 283

    CmdletProvider 283DriveCmdletProvider 287ItemCmdletProvider 288ContainerCmdletProvider 290NavigationCmdletProvider 294IContentCmdletProvider 295IContentReader 296IContentWriter 297IPropertyCmdletProvider 297IDynamicPropertyCmdletProvider 298

    Appendix E: Core Cmdlets for Provider Interaction 303

    Drive-Specific Cmdlets 303Item-Specific Cmdlets 303Container-Specific Cmdlets 304Property-Specific Cmdlets 304Dynamic Property Manipulation Cmdlets 305Content-Related Cmdlets 305Security Descriptor–Related Cmdlets 305

    Index 307

    xvi

  • Kumaravel flast.tex V2 - 01/07/2008 10:54pm Page xvii

    Pre face

    Welcome to Professional Windows PowerShell Programming.

    Way back in 2003, I attended a talk at a conference center at Microsoft by some engineers from theMicrosoft Management Console team who were giving a demonstration of a prototype enhancementto MMC. The prototype was one of the early murmurs of Microsoft’s response to the deluge of customerfeedback they’d received about the Windows administrative user experience after the delivery of theirfirst truly Internet-focused server operating system, Windows 2000 Server. The feedback wasn’t all good.

    Windows 2000 Server started its long evolution as a text-based file manager for DOS. During the bulkof its development, there was simply no idea that anyone would use it for anything other than checkingtheir mail and organizing a 20-megabyte hard disk. As a result, the management story for Windows 2000Server was provided in The Windows Way, which was a rich interactive experience, a full set of nativeand COM APIs, and no bridge between the two. In Linux, you could write a shell script to configure yourmail and DNS servers; in Windows, you had to either do it manually or learn C++ and COM.

    The incorporation of Visual Basic Script and JavaScript into Windows served this niche to a certainextent, but never really brought parity between the GUI experience and the command-line experience.Since these scripting languages interact with the operating system through a subset of COM, and a GUIapplication can use all of COM, call the Win32 API, and (in the case of certain programs such as TaskManager) call directly into the native kernel API, the capabilities of Windows scripts were alwayseclipsed by what was provided in the GUI.

    But back to the demo: People filed into the room, a pair of engineers behind the podium broke the iceby joking about the PA system, the lights dimmed, and they started the show. The new MMC prototype,they revealed, was a GUI that used a command-line engine as its API layer. Every node expansion becamea query, every ‘‘OK’’ click became a command, and every action taken by the GUI operator was displayedas script at the bottom of the screen with 100% fidelity. Old engineers shifted nervously in their seats,senior managers sat entranced with dollar signs in their eyes, and the caterer, noticing the direction ofeveryone’s eyes, palmed an hors d’oeuvre and went outside to smoke a cigarette.

    This demo ushered in what, in the following three years, would become Windows PowerShell.Version 1, available for download on the web and as an optional component on Windows Server 2008,provides a rich programming environment for users of every stripe, and for the first time gives Windowsusers a consistent glide path from the command-line experience all the way to COM and beyond.

    This book is intended for the PowerShell snap-in and host developer audience, and introduces the readerto PowerShell programming from the API level. Written by members of the PowerShell v1.0 team, itcovers development of cmdlets, providers, snap-ins, hosting applications, and custom host implementa-tions in greater depth than the SDK documentation.

    Enjoy.

  • Kumaravel flast.tex V2 - 01/07/2008 10:54pm Page xviii

  • Kumaravel fintro.tex V2 - 01/08/2008 12:14am Page xix

    I n t roduc t ion

    ConventionsTo help you get the most from the text and keep track of what’s happening, we’ve used a number ofconventions throughout the book.

    Boxes like this one hold important, not-to-be-forgotten information that is directlyrelevant to the surrounding text.

    Notes to the current discussion are offset and placed in italics like this.

    As for styles in the text:

    ❑ We highlight new terms and important words when we introduce them.

    ❑ We show keyboard strokes like this: Ctrl+A.❑ Filenames, URLs, and code within the text appear like so: persistence.properties.

    ❑ We present code in two different ways:

    We use a monofont type with no highlighting for most code examples.

    We use gray highlighting to emphasize code that’s particularly importantin the present context.

    Source CodeAs you work through the examples in this book, you may choose either to type in all the code manually orto use the source code files that accompany the book. All of the source code used in this book is availablefor download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Searchbox or by using one of the title lists) and click the Download Code link on the book’s detail page to obtainall the source code for the book. Because many books have similar titles, you may find it easiest to searchby ISBN; this book’s ISBN is 978-0-470-17393-0.

    Once you download the code, just decompress it with your favorite compression tool. Alternatively, youcan go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to seethe code available for this book and all other Wrox books.

  • Kumaravel fintro.tex V2 - 01/08/2008 12:14am Page xx

    Introduction

    ErrataWe make every effort to ensure that there are no errors in the text or in the code. However, no one isperfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or afaulty piece of code, we would be very grateful for your feedback. By sending in errata, you may saveanother reader hours of frustration, and at the same time you will be helping us provide even higherquality information.

    To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or oneof the title lists. Then, on the book details page, click the Book Errata link. On this page you can view allerrata that has been submitted for this book and posted by Wrox editors. A complete book list, includinglinks to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

    If you don’t spot ‘‘your’’ error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the informationand, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editionsof the book.

    p2p.wrox.comFor author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based sys-tem for you to post messages relating to Wrox books and related technologies and to interact with otherreaders and technology users. The forums offer a subscription feature to e-mail you topics of interest ofyour choosing when new posts are made to the forums. Wrox authors, editors, other industry experts,and your fellow readers are present on these forums.

    At http://p2p.wrox.com you will find a number of different forums that will help you not only as youread this book, but also as you develop your own applications. To join the forums, just follow these steps:

    1. Go to p2p.wrox.com and click the Register link.2. Read the terms of use and click Agree.3. Complete the required information to join as well as any optional information you wish to

    provide and click Submit.

    4. You will receive an e-mail with information describing how to verify your account andcomplete the joining process.

    You can read messages in the forums without joining P2P but in order to post your own messages, youmust join.

    Once you join, you can post new messages and respond to messages other users post. You can readmessages at any time on the Web. If you would like to have new messages from a particular forume-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

    For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers toquestions about how the forum software works as well as many common questions specific to P2P andWrox books. To read the FAQs, click the FAQ link on any P2P page.

    xx

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 1

    Introduction to PowerShell

    Welcome to Windows PowerShell, the new object-based command-line interface shell and scriptinglanguage built on top of .NET. PowerShell provides improved control and automation of IT admin-istration tasks for the Windows platform. It is designed to make IT professionals and developersmore productive.

    Several books that introduce end-user IT professionals to Windows PowerShell are already avail-able, but PowerShell development from the perspective of cmdlet, provider, and host developershas gone largely unmentioned. This book attempts to fill that gap by introducing the reader to theconcepts, components, and development techniques behind building software packages that lever-age Windows PowerShell. This book is written for developers who want to extend the functionalityof Windows PowerShell and extend their applications using PowerShell.

    Traditionally, when developers write a command-line utility, they have to write code for parsingthe parameters, binding the argument values to parameters during runtime. In addition, they haveto write code for formatting the output generated by the command. Windows PowerShell makesthat easy by providing a runtime engine with its own parser. It also provides functionality thatenables developers to add custom formatting when their objects are displayed. By performingthe common tasks associated with writing command-line utilities, Windows PowerShell enablesdevelopers to focus on the business logic of their application, rather than spend development timesolving universal problems.

    Windows PowerShell Design PrinciplesWindows PowerShell was designed in response to years of customer feedback about the adminis-trative experience on Microsoft Windows. Early on, many users asked why some of the traditionalUnix shells weren’t licensed and included in Windows, and it became apparent that the right answerwas to produce a whole new kind of shell that would leave these legacy technologies behind. Thisthinking was distilled into four guiding principles that provided the foundation for PowerShell’sdesign effort.

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 2

    Chapter 1: Introduction to PowerShell

    Preserve the Customer’s Existing InvestmentWhen a new technology is rolled out, it takes time for the technology to be adopted. Moreover, customersare likely to have already invested a lot in existing technologies. It’s unreasonable to expect people tothrow out their existing investments, which is why PowerShell was designed from the ground up to becompatible with existing Windows Management technologies.

    In fact, PowerShell runs existing commands and scripts seamlessly. You can make use of PowerShell’sintegration with COM, WMI, and ADSI technologies alongside its tight integration with .NET. Indeed,PowerShell is the only technology that enables you to create and work with objects from these varioustechnologies in one environment. You can see examples of this and other design principles in a quicktour of PowerShell later in the chapter.

    Provide a Powerful, Object-Oriented ShellCMD.exe and other traditional shells are text-based, meaning that the commands in these shells take textas input and produce text as output. Even if these commands convert the text internally into objects, whenthey produce output they convert it back to text. In traditional shells, when you want to put togethersimple commands in the pipeline, a lot of text processing is done between commands to produce desiredoutput. Tools such as SED, AWK, and Perl became popular among command-line scripters because oftheir powerful text-processing capabilities.

    PowerShell is built on top of .NET and is an object-based shell and scripting language. When you pipecommands, PowerShell passes objects between commands in the pipeline. This enables objects to bemanipulated directly and to be passed to other tools. PowerShell’s tight integration with .NET brings thefunctionality and consistency of .NET to IT professionals without requiring them to master a high-levelprogramming language such as C# or VB.NET.

    Extensibility, Extensibility, ExtensibilityThis design principle aims to make the IT administrator more productive by providing greater controlover the Windows environment and accelerating the automation of system administration. Adminis-trators can start PowerShell and use it immediately without having to learn anything because it runsexisting commands and scripts, and is therefore easy to adopt. It is an easy to use shell and language foradministrators.

    All commands in PowerShell are called cmdlets (pronounced ‘‘commandlet’’), and they use verb-nounsyntax — for example, Start-Service, Stop-Service or Get-Process, Get-WMIObject, and so on. Theintuitive nature of verb-noun syntax makes learning commands easy for administrators. PowerShellincludes more than 100 commands and utilities that are admin focused. In addition, PowerShell providesa powerful scripting language that supports a wide range of scripting styles, from simple to sophisticated.This enables administrators to write simple scripts and learn the language as they go. With this combinedfunctionality and ease of use, PowerShell provides a powerful environment for administrators to performtheir daily tasks.

    Tear Down the Barriers to DevelopmentAnother design principle of PowerShell is to make it easy for developers to create command-line toolsand utilities. It provides common argument parsing code, parameter binding code that enables

    2

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 3

    Chapter 1: Introduction to PowerShell

    developers to write code only for the admin functionality they are providing. The PowerShell devel-opment model separates the processing of objects from formatting and outputting. PowerShell providesa set of cmdlets for manipulating objects, formatting objects, and outputting objects. This eliminates theneed for developers to write this code. PowerShell leverages the power of .NET, which enables develop-ers to take advantage of the vast library of this framework. It provides common functionality for logging,error handling, and debugging and tracing capabilities.

    A Quick Tour of Windows PowerShellThis section presents a quick tour of Windows PowerShell. We’ll start with a brief look at installing theprogram, and then move right into a discussion of cmdlets.

    You start Windows PowerShell either by clicking the Windows PowerShell shortcut link or by typingPowerShell in the Run dialog box (see Figure 1-1).

    Figure 1-1: Click the shortcut link and you’ll get the prompt shown here.

    CmdletsWindows PowerShell enables access to several types of commands, including functions, filters, scripts,aliases, cmdlets, and executables (applications). PowerShell’s native command type is the cmdlet. Acmdlet is a simple command used for interacting with any management entity, including the operatingsystem. You can think of a cmdlet as equivalent to a built-in command in another shell. The traditionalshell generally processes commands as separate executables, but a cmdlet is an instance of a .NET class,and runs within PowerShell’s process.

    3

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 4

    Chapter 1: Introduction to PowerShell

    Windows PowerShell provides a rich set of cmdlets, including several that enhance the discoverability ofthe shell’s features. We begin our tour of Windows PowerShell by learning about a few cmdlets that willhelp you get started in this environment. The first cmdlet you need to know about is get-help:

    PS C:\> get-helpTOPIC

    Get-Help

    SHORT DESCRIPTIONDisplays help about PowerShell cmdlets and concepts.

    LONG DESCRIPTION

    SYNTAXget-help { | }help { | } -?

    "Get-help" and "-?" display help on one page."Help" displays help on multiple pages.

    Examples:get-help get-process : Displays help about the get-process cmdlet.get-help about-signing : Displays help about the signing concept.help where-object : Displays help about the where-object cmdlet.help about_foreach : Displays help about foreach loops in PowerShell.match-string -? : Displays help about the match-string cmdlet.

    You can use wildcard characters in the help commands (not with -?).If multiple help topics match, PowerShell displays a list of matchingtopics. If only one help topic matches, PowerShell displays the topic.

    Examples:get-help * : Displays all help topics.get-help get-* : Displays topics that begin with get-.help *object* : Displays topics with "object" in the name.get-help about* : Displays all conceptual topics.

    For information about wildcards, type:get-help about_wildcard

    REMARKS

    4

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 5

    Chapter 1: Introduction to PowerShell

    To learn about PowerShell, read the following help topics:get-command : Displays a list of cmdlets.about_object : Explains the use of objects in PowerShell.get-member : Displays the properties of an object.

    Conceptual help files are named "about_", such as:about_regular_expression.

    The help commands also display the aliases on the system.For information about aliases, type:

    get-help about_alias

    PS C:\>

    As you can see, get-help provides information about how to get help on PowerShell cmdlets and con-cepts. This is all well and good, but you also need to be able to determine what commands are availablefor use. The get-command cmdlet helps you with that:

    PS C:\> get-command

    CommandType Name Definition----------- ---- ----------Cmdlet Add-Content Add-Content [-PCmdlet Add-History Add-History [[-Cmdlet Add-Member Add-Member [-MeCmdlet Add-PSSnapin Add-PSSnapin [-Cmdlet Clear-Content Clear-Content [Cmdlet Clear-Item Clear-Item [-PaCmdlet Clear-ItemProperty Clear-ItemPropeCmdlet Clear-Variable Clear-VariableCmdlet Compare-Object Compare-ObjectCmdlet ConvertFrom-SecureString ConvertFrom-SecCmdlet Convert-Path Convert-Path [-Cmdlet ConvertTo-Html ConvertTo-HtmlCmdlet ConvertTo-SecureString ConvertTo-SecurCmdlet Copy-Item Copy-Item [-Pat

    ...

    As shown in the preceding output, get-command returns all the available commands. You can also findcmdlets with a specific verb or noun:

    PS C:\> get-command -verb get

    CommandType Name Definition----------- ---- ----------Cmdlet Get-Acl Get-Acl [[-Path]Cmdlet Get-Alias Get-Alias [[-NamCmdlet Get-AuthenticodeSignature Get-AuthenticodeCmdlet Get-ChildItem Get-ChildItem [[Cmdlet Get-Command Get-Command [[-A

    5

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 6

    Chapter 1: Introduction to PowerShell

    Cmdlet Get-Content Get-Content [-PaCmdlet Get-Credential Get-Credential [Cmdlet Get-Culture Get-Culture [-VeCmdlet Get-Date Get-Date [[-DateCmdlet Get-EventLog Get-EventLog [-LCmdlet Get-ExecutionPolicy Get-ExecutionPolCmdlet Get-Help Get-Help [[-NameCmdlet Get-History Get-History [[-ICmdlet Get-Host Get-Host [-VerboCmdlet Get-Item Get-Item [-Path]Cmdlet Get-ItemProperty Get-ItemPropertyCmdlet Get-Location Get-Location [-PCmdlet Get-Member Get-Member [[-NaCmdlet Get-PfxCertificate Get-PfxCertificaCmdlet Get-Process Get-Process [[-NCmdlet Get-PSDrive Get-PSDrive [[-NCmdlet Get-PSProvider Get-PSProvider [Cmdlet Get-PSSnapin Get-PSSnapin [[-Cmdlet Get-Runspace Get-Runspace [[-Cmdlet Get-Service Get-Service [[-NCmdlet Get-TraceSource Get-TraceSourceCmdlet Get-UICulture Get-UICulture [-Cmdlet Get-Unique Get-Unique [-InpCmdlet Get-Variable Get-Variable [[-Cmdlet Get-WmiObject Get-WmiObject [-

    When commands are executed, their output is returned to the shell in the form of .NET objects. (In thecase of native commands, the text output of the command is converted to .NET string objects beforebeing returned.) These objects can be directly queried and manipulated by using the object’s propertiesand methods. Fortunately, you don’t have to know the properties and methods of each object in order tomanipulate it. If you’re unfamiliar with an object’s type, you can use the get-member cmdlet to examineits members:

    PS C:\> "Hello" | get-member

    TypeName: System.String

    Name MemberType Definition---- ---------- ----------Clone Method System.Object Clone()CompareTo Method System.Int32 CompareTo(Object value),...Contains Method System.Boolean Contains(String value)CopyTo Method System.Void CopyTo(Int32 sourceIndex,...EndsWith Method System.Boolean EndsWith(String value)...Equals Method System.Boolean Equals(Object obj), Sy...GetEnumerator Method System.CharEnumerator GetEnumerator()GetHashCode Method System.Int32 GetHashCode()GetType Method System.Type GetType()GetTypeCode Method System.TypeCode GetTypeCode()get_Chars Method System.Char get_Chars(Int32 index)get_Length Method System.Int32 get_Length()IndexOf Method System.Int32 IndexOf(Char value, Int3...

    6

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 7

    Chapter 1: Introduction to PowerShell

    IndexOfAny Method System.Int32 IndexOfAny(Char[] anyOf,...Insert Method System.String Insert(Int32 startIndex...IsNormalized Method System.Boolean IsNormalized(), System...LastIndexOf Method System.Int32 LastIndexOf(Char value, ...LastIndexOfAny Method System.Int32 LastIndexOfAny(Char[] an...Normalize Method System.String Normalize(), System.Str...PadLeft Method System.String PadLeft(Int32 totalWidt...PadRight Method System.String PadRight(Int32 totalWid...Remove Method System.String Remove(Int32 startIndex...Replace Method System.String Replace(Char oldChar, C...Split Method System.String[] Split(Params Char[] s...StartsWith Method System.Boolean StartsWith(String valu...Substring Method System.String Substring(Int32 startIn...ToCharArray Method System.Char[] ToCharArray(), System.C...ToLower Method System.String ToLower(), System.Strin...ToLowerInvariant Method System.String ToLowerInvariant()ToString Method System.String ToString(), System.Stri...ToUpper Method System.String ToUpper(), System.Strin...ToUpperInvariant Method System.String ToUpperInvariant()Trim Method System.String Trim(Params Char[] trim...TrimEnd Method System.String TrimEnd(Params Char[] t...TrimStart Method System.String TrimStart(Params Char[]...Chars ParameterizedProperty System.Char Chars(Int32 index) {get;}Length Property System.Int32 Length {get;}

    Windows PowerShell also enables you to execute existing native operating system commands and scripts.The following example executes the ipconfig.exe command to find out about network settings:

    PS C:\> ipconfigWindows IP ConfigurationWireless LAN adapter Wireless Network Connection:

    Connection-specific DNS Suffix . : ARULHOMELANLink-local IPv6 Address . . . . . : fe80::c4e0:69b3:5d35:9b4b%9IPv4 Address. . . . . . . . . . . : 192.168.1.13Subnet Mask . . . . . . . . . . . : 255.255.255.0Default Gateway . . . . . . . . . : 192.168.1.1

    In a traditional shell, when you want to get the IP address output by the IPConfig.exe utility, youhave to perform text parsing. For example, you might do something like get the ninth line of textfrom the output and then get the characters starting from the thirty-ninth character until the end ofthe line to get the IP address. PowerShell enables you to perform this style of traditional text processing,as shown here:

    PS C:\Users\arulk> $a = ipconfigPS C:\Users\arulk> $a[8]

    IPv4 Address. . . . . . . . . . . : 192.168.1.13PS C:\Users\arulk> $a[10].Substring(39)192.168.1.13

    However, this kind of text processing is very brittle and error prone. If the output of IPconfig.exechanges, then the preceding script breaks. For example, because PowerShell converts to text output

    7

  • Kumaravel c01.tex V2 - 01/07/2008 11:14am Page 8

    Chapter 1: Introduction to PowerShell

    by exes and scripts as String objects, it is possible to achieve better text processing. In the precedingexample, we are looking for the line that contains IP in the text:

    PS C:\> $match = @($a | select-string "IP")PS C:\> $ipstring = $match[0].linePS C:\> $ipstring

    IPv4 Address. . . . . . . . . . . : 192.168.1.13PS C:\> $index = $ipstring.indexof(": ")PS C:\> $ipstring.Substring($index+2)PS C:\> $ipaddress = [net.ipaddress]$ipstring.Substring($index+2)PS C:\> $ipaddress

    In the preceding script, the first line searches for the string IP in the result variable $a. @(. . .) and convertsthe result of execution into an array. The reason we do this is because we will get multiple lines thatmatch the IP in computers that have multiple network adapters. We are going to find out the ipaddressin the first adapter. The result returned by select-string is a MatchInfo object. This object containsa member Line that specifies the actual matching line. (I know this because I used get-member to findout.) This string contains the IP address after the characters ": ". Because the Line property is a Stringobject, you use the String object’s IndexOf method (again, I used get-member) to determine the locationwhere the IP address starts. You then use Substring with an index of + 2 (for ": " characters) to get theIP address string. Next, you convert the IP address string into the .NET IPAddress object, which providesmore type safety. As you can see, Windows PowerShell provides great functionality for doing traditionaltext processing.

    Next, let’s look at the COM support in PowerShell:

    PS C:\> $ie = new-object -com internetexplorer.applicationPS C:\> $ie.Navigate2("http://blogs.msdn.com/powershell")PS C:\> $ie.visible = $truePS C:\> $ie.Quit()

    You can create COM objects using the new-object cmdlet, with the -com parameter specifying the pro-grammatic ID of the COM class. In the preceding example, we create an Internet Explorer object andnavigate to the blog of the Windows PowerShell team. As before, you can use get-member to find out allthe properties and methods a COM object supports. Do you see a pattern here?

    In addition to COM, PowerShell also has great support for WMI.:

    PS C:\Users\arulk> $a = get-wmiobject win32_biosPS C:\Users\arulk> $a

    SMBIOSBIOSVersion : Version 1.50Manufacturer : TOSHIBAName : v1.50VSerialNumber : 76047600HVersion : TOSHIB - 970814

    Using get-wmiobject, you can create any WMI object. The preceding example creates an instance of aWin32_Bios object.

    Now that you’ve seen some of PowerShell’s capabilities firsthand, let’s take a look at what goes on underthe hood while you’re providing this functionality to the shell’s user.

    8