Windows PowerShell Cookbook - LinuxCLG

Transcription

Windows PowerShell Cookbook

SECOND EDITIONWindows PowerShell CookbookLee HolmesBeijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Windows PowerShell Cookbook, Second Editionby Lee HolmesCopyright 2010 Lee Holmes. All rights reserved.Printed in the United States of America.Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.O’Reilly books may be purchased for educational, business, or sales promotional use. Online editionsare also available for most titles (http://my.safaribooksonline.com). For more information, contact ourcorporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.Editor: Mike HendricksonProduction Editor: Teresa ElseyCopyeditor: Genevieve d’EntremontProofreader: Teresa ElseyIndexer: Newgen North America, Inc.Cover Designer: Karen MontgomeryInterior Designer: David FutatoIllustrator: Robert RomanoPrinting History:October 2007:August 2010:First Edition.Second Edition.Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks ofO’Reilly Media, Inc. Windows PowerShell Cookbook, the image of a box turtle, and related trade dressare trademarks of O’Reilly Media, Inc.Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of atrademark claim, the designations have been printed in caps or initial caps.While every precaution has been taken in the preparation of this book, the publisher and authors assumeno responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.ISBN: 978-0-596-80150-2[M]1281554603

Table of ContentsForeword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviiForeword to the First Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvPart I. TourA Guided Tour of Windows PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Part II. Fundamentals1. The Windows PowerShell Interactive Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151.161.17Run Programs, Scripts, and Existing ToolsResolve Errors Calling Native ExecutablesRun a PowerShell CommandInvoke a Long-Running or Background CommandNotify Yourself of Job CompletionCustomize Your Shell, Profile, and PromptFind a Command to Accomplish a TaskGet Help on a CommandProgram: Search Help for TextProgram: View PowerShell’s HTML HelpLaunch PowerShell at a Specific LocationInvoke a PowerShell Command or Script from Outside PowerShellCustomize the Shell to Improve Your ProductivityProgram: Learn Aliases for Common CommandsProgram: Learn Aliases for Common ParametersAccess and Manage Your Console HistoryProgram: Create Scripts from Session History1921232427283132343637384042444648v

1.181.191.201.211.221.231.241.251.26Invoke a Command from Your Session HistoryProgram: Search Formatted Output for a PatternInteractively View and Process Command OutputStore the Output of a Command into a FileAdd Information to the End of a FileRecord a Transcript of Your Shell SessionExtend Your Shell with Additional CommandsUse Commands from Customized ShellsSave State Between Sessions4951525455555657592. Pipelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632.12.22.32.42.52.62.72.82.92.10Filter Items in a List or Command OutputGroup and Pivot Data by NameProgram: Simplify Most Where-Object FiltersProgram: Interactively Filter Lists of ObjectsWork with Each Item in a List or Command OutputAutomate Data-Intensive TasksProgram: Simplify Most Foreach-Object PipelinesIntercept Stages of the PipelineAutomatically Capture Pipeline OutputCapture and Redirect Binary Process Output646568707274788081833. Variables and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153.163.17Display the Properties of an Item as a ListDisplay the Properties of an Item as a TableStore Information in VariablesAccess Environment VariablesProgram: Retain Changes to Environment Variables Set by a BatchFileControl Access and Scope of Variables and Other ItemsProgram: Create a Dynamic VariableWork with .NET ObjectsCreate an Instance of a .NET ObjectProgram: Create Instances of Generic ObjectsReduce Typing for Long Class NamesUse a COM ObjectLearn About Types and ObjectsGet Detailed Documentation About Types and ObjectsAdd Custom Methods and Properties to ObjectsCreate and Initialize Custom ObjectsAdd Custom Methods and Properties to Typesvi Table of 1125

4. Looping and Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1314.14.24.34.44.5Make Decisions with Comparison and Logical OperatorsAdjust Script Flow Using Conditional StatementsManage Large Conditional Statements with SwitchesRepeat Operations with LoopsAdd a Pause or Delay1311331351361395. Strings and Unstructured Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.155.16Create a StringCreate a Multiline or Formatted StringPlace Special Characters in a StringInsert Dynamic Information in a StringPrevent a String from Including Dynamic InformationPlace Formatted Information in a StringSearch a String for Text or a PatternReplace Text in a StringSplit a String on Text or a PatternCombine Strings into a Larger StringConvert a String to Upper/LowercaseTrim a StringFormat a Date for OutputProgram: Convert Text Streams to ObjectsGenerate Large Reports and Text StreamsGenerate Source Code and Other Repetitive 666. Calculations and Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1716.16.26.36.46.56.6Perform Simple ArithmeticPerform Complex ArithmeticMeasure Statistical Properties of a ListWork with Numbers as BinarySimplify Math with Administrative ConstantsConvert Numbers Between Bases1711731751771801817. Lists, Arrays, and Hashtables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1837.17.27.37.47.57.67.77.87.9Create an Array or List of ItemsCreate a Jagged or Multidimensional ArrayAccess Elements of an ArrayVisit Each Element of an ArraySort an Array or List of ItemsDetermine Whether an Array Contains an ItemCombine Two ArraysFind Items in an Array That Match a ValueCompare Two Lists183185186188189190191192193Table of Contents vii

7.107.117.127.137.14Remove Elements from an ArrayFind Items in an Array Greater or Less Than a ValueUse the ArrayList Class for Advanced Array TasksCreate a Hashtable or Associative ArraySort a Hashtable by Key or Value1931941951971988. Utility Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2018.18.28.38.48.58.6Get the System Date and TimeMeasure the Duration of a CommandRead and Write from the Windows ClipboardGenerate a Random Number or ObjectProgram: Search the Windows Start MenuProgram: Show Colorized Script Content201202203206208209Part III. Common Tasks9. Simple Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2179.19.29.39.49.59.69.79.8Get the Content of a FileSearch a File for Text or a PatternParse and Manage Text-Based LogfilesParse and Manage Binary FilesCreate a Temporary FileSearch and Replace Text in a FileProgram: Get the Encoding of a FileProgram: View the Hexadecimal Representation of Content21721922222422722823123310. Structured Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23710.110.210.310.410.510.610.710.810.9Access Information in an XML FilePerform an XPath Query Against XMLConvert Objects to XMLModify Data in an XML FileEasily Import and Export Your Structured DataStore the Output of a Command in a CSV or Delimited FileImport CSV and Delimited Data from a FileUse Excel to Manage Command OutputParse and Interpret PowerShell Scripts23724024224324524724824925111. Code Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25511.111.211.311.4Write a ScriptWrite a FunctionFind a Verb Appropriate for a Command NameWrite a Script Blockviii Table of Contents255258260261

11.1611.1711.1811.1911.2011.2111.2211.23Return Data from a Script, Function, or Script BlockPackage Common Commands in a ModuleWrite Commands That Maintain StateSelectively Export Commands from a ModuleDiagnose and Interact with Internal Module StateHandle Cleanup Tasks When a Module Is RemovedAccess Arguments of a Script, Function, or Script BlockAdd Validation to ParametersAccept Script Block Parameters with Local VariablesDynamically Compose Command ParametersProvide -WhatIf, -Confirm, and Other Cmdlet FeaturesAdd Help to Scripts or FunctionsAdd Custom Tags to a Function or Script BlockAccess Pipeline InputWrite Pipeline-Oriented Scripts with Cmdlet KeywordsWrite a Pipeline-Oriented FunctionOrganize Scripts for Improved ReadabilityInvoke Dynamically Named CommandsProgram: Enhance or Extend an Existing 630030130330412. Internet-Enabled Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31312.112.212.312.412.512.612.712.812.9Download a File from the InternetDownload a Web Page from the InternetProgram: Get-PageUrlsConnect to a Web ServiceProgram: Connect-WebServiceExport Command Output as a Web PageSend an EmailProgram: Send-MailMessageProgram: Interact with Internet Protocols31331431832132332632732832913. User Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ead a Line of User InputRead a Key of User InputProgram: Display a Menu to the UserDisplay Messages and Output to the UserProvide Progress Updates on Long-Running TasksWrite Culture-Aware ScriptsSupport Other Languages in Script OutputProgram: Invoke a Script Block with Alternate Culture SettingsAccess Features of the Host’s User InterfaceProgram: Add a Graphical User Interface to Your ScriptInteract with UI Frameworks and STA Objects335336337339342344347349350352355Table of Contents ix

14. Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35914.114.214.314.414.514.614.714.8Prevent Common Scripting ErrorsTrace Script ExecutionSet a Script BreakpointDebug a Script When It Encounters an ErrorCreate a Conditional BreakpointInvestigate System State While DebuggingProgram: Watch an Expression for ChangesProgram: Get Script Code Coverage36036236536837037237537715. Tracing and Error Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38115.115.215.315.415.515.615.715.8Determine the Status of the Last CommandView the Errors Generated by a CommandManage the Error Output of CommandsProgram: Resolve an ErrorConfigure Debug, Verbose, and Progress OutputHandle Warnings, Errors, and Terminating ErrorsOutput Warnings, Errors, and Terminating ErrorsProgram: Analyze a Script’s Performance Profile38138338538638738939239316. Environmental Awareness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39916.116.216.316.416.516.616.716.816.916.10View and Modify Environment VariablesAccess Information About Your Command’s InvocationProgram: Investigate the InvocationInfo VariableFind Your Script’s NameFind Your Script’s LocationFind the Location of Common System PathsGet the Current LocationSafely Build File Paths Out of Their ComponentsInteract with PowerShell’s Global EnvironmentDetermine PowerShell Version Information39940140340540640740941141141217. Extend the Reach of Windows PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . te Programs Using COM Scripting InterfacesProgram: Query a SQL Data SourceAccess Windows Performance CountersAccess Windows API FunctionsProgram: Invoke Simple Windows API CallsDefine or Extend a .NET ClassAdd Inline C# to Your PowerShell ScriptAccess a .NET SDK LibraryCreate Your Own PowerShell CmdletAdd PowerShell Scripting to Your Own Programx Table of Contents415416419422428431434436438440

18. Security and Script Signing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.1218.1318.1418.1518.16Enable Scripting Through an Execution PolicyDisable Warnings for UNC PathsSign a PowerShell Script, Module, or Formatting FileProgram: Create a Self-Signed CertificateManage PowerShell Security in an EnterpriseBlock Scripts by Publisher, Path, or HashVerify the Digital Signature of a PowerShell ScriptSecurely Handle Sensitive InformationSecurely Request Usernames and PasswordsProgram: Start a Process as Another UserProgram: Run a Temporarily Elevated CommandSecurely Store Credentials on DiskAccess User and Machine CertificatesProgram: Search the Certificate StoreAdd and Remove CertificatesManage Security Descriptors in SDDL 7119. Integrated Scripting Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47319.119.219.319.419.5Debug a ScriptCustomize Text and User Interface ColorsConnect to a Remote ComputerExtend ISE Functionality Through Its Object ModelAdd an Item to the Tools Menu475477479479481Part IV. Administrator Tasks20. Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0.1220.1320.14Determine the Current LocationGet the Files in a DirectoryFind All Files Modified Before a Certain DateClear the Content of a FileManage and Change the Attributes of a FileFind Files That Match a PatternManage Files That Include Special CharactersProgram: Get Disk Usage InformationMonitor a File for ChangesGet the Version of a DLL or ExecutableProgram: Get the MD5 or SHA1 Hash of a FileCreate a DirectoryRemove a File or DirectoryRename a File or 2Table of Contents xi

20.1520.1620.1720.1820.1920.2020.21Move a File or DirectoryProgram: Move or Remove a Locked FileGet the ACL of a File or DirectorySet the ACL of a File or DirectoryProgram: Add Extended File Properties to FilesProgram: Create a Filesystem Hard LinkProgram: Create a ZIP Archive50450450650850951151321. The Windows Registry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1221.1321.1421.1521.16Navigate the RegistryView a Registry KeyModify or Remove a Registry Key ValueCreate a Registry Key ValueRemove a Registry KeySafely Combine Related Registry ModificationsAdd a Site to an Internet Explorer Security ZoneModify Internet Explorer SettingsProgram: Search the Windows RegistryGet the ACL of a Registry KeySet the ACL of a Registry KeyWork with the Registry of a Remote ComputerProgram: Get Registry Items from Remote MachinesProgram: Get Properties of Remote Registry KeysProgram: Set Properties of Remote Registry KeysDiscover Registry Settings for 53753922. Comparing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54322.1 Compare the Output of Two Commands22.2 Determine the Differences Between Two Files22.3 Verify Integrity of File Sets54354554523. Event Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ist All Event LogsGet the Newest Entries from an Event LogFind Event Log Entries with Specific TextRetrieve and Filter Event Log EntriesFind Event Log Entries by Their FrequencyBack Up an Event LogCreate or Remove an Event LogWrite to an Event LogRun a PowerShell Script for Windows Event Log EntriesClear or Maintain an Event LogAccess Event Logs of a Remote Machinexii Table of Contents549551552553556558560561562563565

24. Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56924.124.224.324.424.5List Currently Running ProcessesLaunch the Application Associated with a DocumentLaunch a ProcessStop a ProcessDebug a Process57057157257357525. System Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57725.1 List All Running Services25.2 Manage a Running Service25.3 Configure a Service57757958026. Active Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2226.2326.24Test Active Directory Scripts on a Local InstallationCreate an Organizational UnitGet the Properties of an Organizational UnitModify Properties of an Organizational UnitDelete an Organizational UnitGet the Children of an Active Directory ContainerCreate a User AccountProgram: Import Users in Bulk to Active DirectorySearch for a User AccountGet and List the Properties of a User AccountModify Properties of a User AccountChange a User PasswordCreate a Security or Distribution GroupSearch for a Security or Distribution GroupGet the Properties of a GroupFind the Owner of a GroupModify Properties of a Security or Distribution GroupAdd a User to a Security or Distribution GroupRemove a User from a Security or Distribution GroupList a User’s Group MembershipList the Members of a GroupList the Users in an Organizational UnitSearch for a Computer AccountGet and List the Properties of a Computer 9759859960060060160260260360427. Enterprise Computer Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60727.127.227.327.4Join a Computer to a Domain or WorkgroupRemove a Computer from a DomainProgram: List Logon or Logoff Scripts for a UserProgram: List Startup or Shutdown Scripts for a Machine607608609610Table of Contents xiii

27.1627.1727.1827.1927.2027.21Deploy PowerShell-Based Logon ScriptsEnable or Disable the Windows FirewallOpen or Close Ports in the Windows FirewallProgram: List All Installed SoftwareUninstall an ApplicationManage Computer Restore PointsReboot or Shut Down a ComputerDetermine Whether a Hotfix Is InstalledManage Scheduled Tasks on a ComputerRetrieve Printer InformationRetrieve Printer Queue StatisticsManage Printers and Print QueuesProgram: Summarize System InformationRenew a DHCP LeaseAssign a Static IP AddressList All IP Addresses for a ComputerList Network Adapter 2762963063128. Windows Management Instrumentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63328.128.228.328.428.528.628.728.8Access Windows Management Instrumentation DataModify the Properties of a WMI InstanceInvoke a Method on a WMI ClassProgram: Determine Properties Available to WMI FiltersProgram: Search for WMI ClassesUse .NET to Perform Advanced WMI TasksImprove the Performance of Large-Scale WMI OperationsConvert a VBScript WMI Script to PowerShell63563763964064264564664729. Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.1229.1329.14Find Commands That Support Their Own RemotingProgram: Invoke a PowerShell Expression on a Remote MachineTest Connectivity Between Two ComputersLimit Networking Scripts to Hosts That RespondEnable PowerShell Remoting on a ComputerEnable Remote Desktop on a ComputerProgram: Remotely Enable PowerShell RemotingConfigure User Permissions for RemotingEnable Remoting to Workgroup ComputersInteractively Manage a Remote ComputerInvoke a Command on a Remote ComputerImplicitly Invoke Commands from a Remote ComputerCreate Sessions with Full Network AccessPass Variables to Remote Sessionsxiv Table of Contents652653656658659661662664665667669673676680

29.1529.1629.1729.1829.1929.20Configure Advanced Remoting OptionsInvoke a Command on Many ComputersRun a Local Script on a Remote ComputerProgram: Transfer a File to a Remote ComputerDetermine Whether a Script Is Running on a Remote ComputerProgram: Create a Task-Specific Remoting Endpoint68168368468568868830. Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69330.1 Safely Experiment with Transactions30.2 Change Error Recovery Behavior in Transactions69569731. Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69931.131.231.331.431.531.6Respond to Automatically Generated EventsCreate and Respond to Custom EventsCreate a Temporary Event SubscriptionForward Events from a Remote ComputerInvestigate Internal Event Action StateUse a Script Block as a .NET Delegate or Event Handler700703706707708710Part V. ReferencesA. PowerShell Language and Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715B. Regular Expression Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765C. XPath Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773D. .NET String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777E. .NET DateTime Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781F. Selected .NET Classes and Their Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787G. WMI Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795H. Selected COM Objects and Their Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803I. Selected Events and Their Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807J. Standard PowerShell Verbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815Table of Contents xv

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821xvi Table of Contents

ForewordAs someone who has written, or contributed to, more than a dozen books, I am wellaware of the incredible amount of work and monumental commitment of time andresources involved with writing a book. That someone would choose to do this atessentially the same time one is burning the midnight oil while developing one of themost exciting products in Microsoft’s history bespeaks a most committed person.However, more than simple commitment is involved. From my conversations with Lee,I can tell that he is passionate about Windows PowerShell. He sees the revolutionarychanges introduced with the 2.0 release of the product. If Windows PowerShell 1.0 wasthe concept, Windows PowerShell 2.0 is the answer. If Windows PowerShell 1.0 wasthe vision, Windows PowerShell 2.0 is the reality. If Windows PowerShell 1.0 was forearly adopters, Windows PowerShell 2.0 is moving into the mainstream.With the inclusion of Windows PowerShell 2.0 in Windows 7 and Windows Server2008 R2, we are beginning to see the commitment Microsoft is making to the product.That the SharePoint, SQL, Exchange, Active Directory Domain Services (AD DS), Internet Information Server (IIS) teams, and others have all made cmdlets should tell youthat Windows PowerShell is not a passing fad. Windows PowerShell questions arealready cropping up on Microsoft Certification Examinations, and as a network administrator or a consultant, you will need to learn Windows PowerShell.Learning Windows PowerShell need not be tedious, boring, or exhausting. In fact, youwill be joining a community that is at least as passionate about Windows PowerShellas Lee (or the rest of the Windows PowerShell team) or me (I write the Hey, ScriptingGuy! blog seven days a week—the only Microsoft blog updated daily, by the way).What other product from Microsoft has inspired a half dozen songs to be written aboutit? Not by the marketing department, but by people who fell in love with WindowsPowerShell, or, better yet, to use the community term: became addicted.I attended a recent SQL Saturday in Charlotte, North Carolina, because I wanted tomeet and interact with members of the Windows PowerShell community. That is right:there is a huge group of hardcore SQL administrators who are adopting WindowsPowerShell because of its cool server management capabilities. In addition, a projectknown as the SQL Server PowerShell Extensions (SQLPSX) module (available fromCodePlex) has wrapped much of the SQL Management Objects (SMO) into more thanxvii

130 useful functions. This provides ease of use for people who are not experts withSQL SMO and Windows PowerShell. By leveraging modules, the community is takingadvantage of one of the great new features of Windows PowerShell 2.0. In fact, thereare more than 200 Windows PowerShell projects on CodePlex. One person presentingat SQL Saturday declared that the active Windows PowerShell community was one ofthe great strengths of Windows PowerShell. You are not alone when it comes to learningand implementing Windows PowerShell.I do not own every Windows PowerShell book ever written. I have probably looked atmost Windows PowerShell books, but I found some of them redundant and someothers confusing. However, a few of the Windows PowerShell books are essential. Lee’s1.0 version of this book fell into that category. I keep it within arm’s length of my deskand grab it often. I have highlighted certain sections, dog-eared others, and placedsticky tabs on the more essential pages. Over the last couple years, Lee’s WindowsPowerShell Cookbook has grown to look more like a skinny porcupine on a bad hairday than a typical scripting book—and that is a good thing, because his book is not atypical scripting book; it is a cookbook. Just like a “real cookbook” that contains recipesfor meals, this fascinating volume is what I find myself thumbing through when I amhungry to try something new with Windows PowerShell.In reviewing Lee’s upgraded Windows PowerShell Cookbook, I see that I will not beplaced on a diet of “foo” and “bar”; instead, there are tasty morsels such as GetPageUrls, a way-cool script that illustrates using regular expressions to extract URLsfrom a downloaded web page. It even fixes relative URLs so that they include the serverfrom which they originated. All this happens faster than you can say “super useful”three times.I found Chapter 14 on debugging to be well worth a careful read. Lee has a number ofreally good points, the premier one being: do not make the mistake in the first place.This echoes my own best practice. Of course, mistakes are made, errors are introduced,and that is when the debugger commands are called upon. Windows PowerShell 2.0ships with some great debugging cmdlets, and Lee has some extremely cool scripts tosimplify the process, or at least to reduce some of the tedium. I really like the WatchExpression script because it automatically displays the values of expressions you wishto track.If Chapter 14 is worth a careful read, Chapter 18 is worth a sticky tab because you willfind yourself coming back to it often. Security and script signing is a subject of muchdebate in the Windows PowerShell community. You will want to hear about securityfrom the horse’s mouth. A common question I hear when giving presentations onWindows PowerShell is “How can I invoke a command as another user without switching contexts?” The genesis of this question is, of course, the Unix sudo command. Leehas a useful script named Invoke-ElevatedCommand that allows you to accomplish thistask. Most excellent.xviii Foreword

One other thing you need to read about is the Windows PowerShell Integrated ScriptingEnvironment (ISE), in Chapter 19. A common request for years was for Microsoft towrite a script editor. For years, I have been telling people we did write a script editor—Notepad. The Windows PowerShell ISE is much better than Notepad. Not only is theWindows PowerShell ISE a great script editor in its own right, but the WindowsPowerShell team also exposed an object model that allows you to modify its behaviorand to configure it to work in the way you wish to work. Lee has a whole section inChapter 19 that talks about the ISE and how to modify it.Working with files, directories, the registry, services, processes, WMI, remoting, transactions, and event handling—it is all in this book. I am not going to go over all that,because I do not want to spoil the plot. Suffice it to

1.10 Program: View PowerShell’s HTML Help 36 1.11 Launch PowerShell at a Specific Location 37 1.12 Invoke a PowerShell Command or Script from Outside PowerShell 38 1.13 Customize the Shell to Improve Your Productivity 40 1.14 Program: Learn Aliases for Common Command