The Windows PowerShell Interactive Shell.. More than just a cookbook, however, the third edition of the Windows PowerShellCookbook is also a textbook of how to write great Windows PowerS
Trang 3Lee Holmes
THIRD EDITIONWindows PowerShell Cookbook
Trang 4ISBN: 978-1-449-32068-3
[LSI]
Windows PowerShell Cookbook, Third Edition
by Lee Holmes
Copyright © 2013 Lee Holmes All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are
also available for most titles (http://my.safaribooksonline.com) For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Rachel Roumeliotis
Production Editor: Kara Ebrahim
Proofreader: Rachel Monaghan
Indexer: Angela Howard
Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrator: Rebecca Demarest October 2007: First Edition
August 2010: Second Edition
January 2013: Third Edition
Revision History for the First Edition:
2012-12-21 First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449320683 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc Windows Powershell Cookbook, the image of a box tortoise, and related trade dress are trademarks
of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
Trang 5Table of Contents
Foreword xvii
Preface xix
Part I Tour A Guided Tour of Windows PowerShell iii
Part II Fundamentals 1 The Windows PowerShell Interactive Shell 19
1.1 Run Programs, Scripts, and Existing Tools 19
1.2 Run a PowerShell Command 23
1.3 Resolve Errors Calling Native Executables 24
1.4 Supply Default Values for Parameters 26
1.5 Invoke a Long-Running or Background Command 28
1.6 Program: Monitor a Command for Changes 32
1.7 Notify Yourself of Job Completion 35
1.8 Customize Your Shell, Profile, and Prompt 36
1.9 Customize PowerShell’s User Input Behavior 39
1.10 Customize PowerShell’s Command Resolution Behavior 40
1.11 Find a Command to Accomplish a Task 43
1.12 Get Help on a Command 45
1.13 Update System Help Content 47
1.14 Program: Search Help for Text 49
1.15 Launch PowerShell at a Specific Location 50
1.16 Invoke a PowerShell Command or Script from Outside PowerShell 52
1.17 Understand and Customize PowerShell’s Tab Completion 55
1.18 Program: Learn Aliases for Common Commands 59
1.19 Program: Learn Aliases for Common Parameters 61
iii
Trang 61.20 Access and Manage Your Console History 64
1.21 Program: Create Scripts from Your Session History 66
1.22 Invoke a Command from Your Session History 68
1.23 Program: Search Formatted Output for a Pattern 69
1.24 Interactively View and Process Command Output 70
1.25 Program: Interactively View and Explore Objects 72
1.26 Store the Output of a Command into a File 79
1.27 Add Information to the End of a File 80
1.28 Record a Transcript of Your Shell Session 81
1.29 Extend Your Shell with Additional Commands 82
1.30 Use Commands from Customized Shells 84
1.31 Save State Between Sessions 85
2 Pipelines 89
2.1 Filter Items in a List or Command Output 90
2.2 Group and Pivot Data by Name 91
2.3 Program: Simplify Most Where-Object Filters 94
2.4 Program: Interactively Filter Lists of Objects 96
2.5 Work with Each Item in a List or Command Output 99
2.6 Automate Data-Intensive Tasks 101
2.7 Program: Simplify Most Foreach-Object Pipelines 105
2.8 Intercept Stages of the Pipeline 108
2.9 Automatically Capture Pipeline Output 109
2.10 Capture and Redirect Binary Process Output 111
3 Variables and Objects 117
3.1 Display the Properties of an Item as a List 118
3.2 Display the Properties of an Item as a Table 120
3.3 Store Information in Variables 122
3.4 Access Environment Variables 123
3.5 Program: Retain Changes to Environment Variables Set by a Batch File 126
3.6 Control Access and Scope of Variables and Other Items 128
3.7 Program: Create a Dynamic Variable 130
3.8 Work with NET Objects 133
3.9 Create an Instance of a NET Object 138
3.10 Create Instances of Generic Objects 140
3.11 Reduce Typing for Long Class Names 141
3.12 Use a COM Object 143
3.13 Learn About Types and Objects 143
3.14 Get Detailed Documentation About Types and Objects 145
3.15 Add Custom Methods and Properties to Objects 147
3.16 Create and Initialize Custom Objects 150
Trang 73.17 Add Custom Methods and Properties to Types 154
3.18 Define Custom Formatting for a Type 158
4 Looping and Flow Control 163
4.1 Make Decisions with Comparison and Logical Operators 163
4.2 Adjust Script Flow Using Conditional Statements 165
4.3 Manage Large Conditional Statements with Switches 167
4.4 Repeat Operations with Loops 170
4.5 Add a Pause or Delay 172
5 Strings and Unstructured Text 175
5.1 Create a String 175
5.2 Create a Multiline or Formatted String 177
5.3 Place Special Characters in a String 178
5.4 Insert Dynamic Information in a String 179
5.5 Prevent a String from Including Dynamic Information 180
5.6 Place Formatted Information in a String 181
5.7 Search a String for Text or a Pattern 183
5.8 Replace Text in a String 185
5.9 Split a String on Text or a Pattern 187
5.10 Combine Strings into a Larger String 190
5.11 Convert a String to Uppercase or Lowercase 191
5.12 Trim a String 193
5.13 Format a Date for Output 194
5.14 Program: Convert Text Streams to Objects 196
5.15 Generate Large Reports and Text Streams 200
5.16 Generate Source Code and Other Repetitive Text 202
6 Calculations and Math 207
6.1 Perform Simple Arithmetic 207
6.2 Perform Complex Arithmetic 209
6.3 Measure Statistical Properties of a List 213
6.4 Work with Numbers as Binary 214
6.5 Simplify Math with Administrative Constants 218
6.6 Convert Numbers Between Bases 219
7 Lists, Arrays, and Hashtables 223
7.1 Create an Array or List of Items 223
7.2 Create a Jagged or Multidimensional Array 225
7.3 Access Elements of an Array 226
7.4 Visit Each Element of an Array 228
7.5 Sort an Array or List of Items 229
Table of Contents | v
Trang 87.6 Determine Whether an Array Contains an Item 230
7.7 Combine Two Arrays 231
7.8 Find Items in an Array That Match a Value 232
7.9 Compare Two Lists 233
7.10 Remove Elements from an Array 234
7.11 Find Items in an Array Greater or Less Than a Value 235
7.12 Use the ArrayList Class for Advanced Array Tasks 236
7.13 Create a Hashtable or Associative Array 238
7.14 Sort a Hashtable by Key or Value 239
8 Utility Tasks 243
8.1 Get the System Date and Time 243
8.2 Measure the Duration of a Command 244
8.3 Read and Write from the Windows Clipboard 246
8.4 Generate a Random Number or Object 248
8.5 Program: Search the Windows Start Menu 250
8.6 Program: Show Colorized Script Content 251
Part III Common Tasks 9 Simple Files 259
9.1 Get the Content of a File 259
9.2 Search a File for Text or a Pattern 261
9.3 Parse and Manage Text-Based Logfiles 264
9.4 Parse and Manage Binary Files 267
9.5 Create a Temporary File 270
9.6 Search and Replace Text in a File 271
9.7 Program: Get the Encoding of a File 275
9.8 Program: View the Hexadecimal Representation of Content 277
10 Structured Files 281
10.1 Access Information in an XML File 281
10.2 Perform an XPath Query Against XML 284
10.3 Convert Objects to XML 286
10.4 Modify Data in an XML File 287
10.5 Easily Import and Export Your Structured Data 289
10.6 Store the Output of a Command in a CSV or Delimited File 291
10.7 Import CSV and Delimited Data from a File 292
10.8 Manage JSON Data Streams 294
10.9 Use Excel to Manage Command Output 295
Trang 910.10 Parse and Interpret PowerShell Scripts 297
11 Code Reuse 303
11.1 Write a Script 303
11.2 Write a Function 306
11.3 Find a Verb Appropriate for a Command Name 308
11.4 Write a Script Block 309
11.5 Return Data from a Script, Function, or Script Block 311
11.6 Package Common Commands in a Module 314
11.7 Write Commands That Maintain State 317
11.8 Selectively Export Commands from a Module 320
11.9 Diagnose and Interact with Internal Module State 322
11.10 Handle Cleanup Tasks When a Module Is Removed 324
11.11 Access Arguments of a Script, Function, or Script Block 325
11.12 Add Validation to Parameters 330
11.13 Accept Script Block Parameters with Local Variables 334
11.14 Dynamically Compose Command Parameters 336
11.15 Provide -WhatIf, -Confirm, and Other Cmdlet Features 338
11.16 Add Help to Scripts or Functions 340
11.17 Add Custom Tags to a Function or Script Block 343
11.18 Access Pipeline Input 345
11.19 Write Pipeline-Oriented Scripts with Cmdlet Keywords 347
11.20 Write a Pipeline-Oriented Function 351
11.21 Organize Scripts for Improved Readability 352
11.22 Invoke Dynamically Named Commands 354
11.23 Program: Enhance or Extend an Existing Cmdlet 356
12 Internet-Enabled Scripts 365
12.1 Download a File from an FTP or Internet Site 365
12.2 Upload a File to an FTP Site 366
12.3 Download a Web Page from the Internet 368
12.4 Parse and Analyze a Web Page from the Internet 373
12.5 Script a Web Application Session 375
12.6 Program: Get-PageUrls 379
12.7 Interact with REST-Based Web APIs 383
12.8 Connect to a Web Service 385
12.9 Export Command Output as a Web Page 387
12.10 Send an Email 388
12.11 Program: Monitor Website Uptimes 389
12.12 Program: Interact with Internet Protocols 391
13 User Interaction 397
Table of Contents | vii
Trang 1013.1 Read a Line of User Input 397
13.2 Read a Key of User Input 398
13.3 Program: Display a Menu to the User 399
13.4 Display Messages and Output to the User 401
13.5 Provide Progress Updates on Long-Running Tasks 404
13.6 Write Culture-Aware Scripts 405
13.7 Support Other Languages in Script Output 409
13.8 Program: Invoke a Script Block with Alternate Culture Settings 412
13.9 Access Features of the Host’s User Interface 414
13.10 Program: Add a Graphical User Interface to Your Script 415
13.11 Interact with MTA Objects 418
14 Debugging 421
14.1 Prevent Common Scripting Errors 422
14.2 Trace Script Execution 424
14.3 Set a Script Breakpoint 428
14.4 Debug a Script When It Encounters an Error 430
14.5 Create a Conditional Breakpoint 432
14.6 Investigate System State While Debugging 434
14.7 Program: Watch an Expression for Changes 437
14.8 Program: Get Script Code Coverage 440
15 Tracing and Error Management 443
15.1 Determine the Status of the Last Command 443
15.2 View the Errors Generated by a Command 445
15.3 Manage the Error Output of Commands 447
15.4 Program: Resolve an Error 448
15.5 Configure Debug, Verbose, and Progress Output 450
15.6 Handle Warnings, Errors, and Terminating Errors 452
15.7 Output Warnings, Errors, and Terminating Errors 455
15.8 Program: Analyze a Script’s Performance Profile 456
16 Environmental Awareness 463
16.1 View and Modify Environment Variables 463
16.2 Modify the User or System Path 465
16.3 Access Information About Your Command’s Invocation 466
16.4 Program: Investigate the InvocationInfo Variable 468
16.5 Find Your Script’s Name 471
16.6 Find Your Script’s Location 472
16.7 Find the Location of Common System Paths 473
16.8 Get the Current Location 476
16.9 Safely Build File Paths Out of Their Components 477
Trang 1116.10 Interact with PowerShell’s Global Environment 478
16.11 Determine PowerShell Version Information 479
16.12 Test for Administrative Privileges 480
17 Extend the Reach of Windows PowerShell 483
17.1 Automate Programs Using COM Scripting Interfaces 483
17.2 Program: Query a SQL Data Source 485
17.3 Access Windows Performance Counters 488
17.4 Access Windows API Functions 490
17.5 Program: Invoke Simple Windows API Calls 497
17.6 Define or Extend a NET Class 500
17.7 Add Inline C# to Your PowerShell Script 503
17.8 Access a NET SDK Library 505
17.9 Create Your Own PowerShell Cmdlet 507
17.10 Add PowerShell Scripting to Your Own Program 510
18 Security and Script Signing 515
18.1 Enable Scripting Through an Execution Policy 516
18.2 Disable Warnings for UNC Paths 519
18.3 Sign a PowerShell Script, Module, or Formatting File 520
18.4 Program: Create a Self-Signed Certificate 522
18.5 Manage PowerShell Security in an Enterprise 523
18.6 Block Scripts by Publisher, Path, or Hash 526
18.7 Verify the Digital Signature of a PowerShell Script 527
18.8 Securely Handle Sensitive Information 529
18.9 Securely Request Usernames and Passwords 531
18.10 Program: Start a Process as Another User 532
18.11 Program: Run a Temporarily Elevated Command 534
18.12 Securely Store Credentials on Disk 537
18.13 Access User and Machine Certificates 539
18.14 Program: Search the Certificate Store 540
18.15 Add and Remove Certificates 542
18.16 Manage Security Descriptors in SDDL Form 543
19 Integrated Scripting Environment 545
19.1 Debug a Script 547
19.2 Customize Text and User Interface Colors 549
19.3 Connect to a Remote Computer 551
19.4 Extend ISE Functionality Through Its Object Model 552
19.5 Quickly Insert Script Snippets 553
Table of Contents | ix
Trang 1219.6 Add an Item to the Tools Menu 555
Part IV Administrator Tasks 20 Files and Directories 559
20.1 Determine the Current Location 560
20.2 Get the Files in a Directory 561
20.3 Find All Files Modified Before a Certain Date 563
20.4 Clear the Content of a File 564
20.5 Manage and Change the Attributes of a File 565
20.6 Find Files That Match a Pattern 566
20.7 Manage Files That Include Special Characters 569
20.8 Program: Get Disk Usage Information 570
20.9 Monitor a File for Changes 572
20.10 Get the Version of a DLL or Executable 573
20.11 Program: Get the MD5 or SHA1 Hash of a File 574
20.12 Create a Directory 576
20.13 Remove a File or Directory 577
20.14 Rename a File or Directory 578
20.15 Move a File or Directory 579
20.16 Create and Map PowerShell Drives 580
20.17 Access Long File and Directory Names 582
20.18 Unblock a File 583
20.19 Interact with Alternate Data Streams 584
20.20 Program: Move or Remove a Locked File 586
20.21 Get the ACL of a File or Directory 587
20.22 Set the ACL of a File or Directory 589
20.23 Program: Add Extended File Properties to Files 591
20.24 Program: Create a Filesystem Hard Link 593
20.25 Program: Create a ZIP Archive 595
21 The Windows Registry 599
21.1 Navigate the Registry 599
21.2 View a Registry Key 600
21.3 Modify or Remove a Registry Key Value 601
21.4 Create a Registry Key Value 602
21.5 Remove a Registry Key 603
21.6 Safely Combine Related Registry Modifications 604
21.7 Add a Site to an Internet Explorer Security Zone 606
21.8 Modify Internet Explorer Settings 608
21.9 Program: Search the Windows Registry 609
Trang 1321.10 Get the ACL of a Registry Key 611
21.11 Set the ACL of a Registry Key 612
21.12 Work with the Registry of a Remote Computer 614
21.13 Program: Get Registry Items from Remote Machines 616
21.14 Program: Get Properties of Remote Registry Keys 618
21.15 Program: Set Properties of Remote Registry Keys 620
21.16 Discover Registry Settings for Programs 622
22 Comparing Data 627
22.1 Compare the Output of Two Commands 627
22.2 Determine the Differences Between Two Files 629
22.3 Verify Integrity of File Sets 630
23 Event Logs 633
23.1 List All Event Logs 633
23.2 Get the Newest Entries from an Event Log 635
23.3 Find Event Log Entries with Specific Text 636
23.4 Retrieve and Filter Event Log Entries 638
23.5 Find Event Log Entries by Their Frequency 641
23.6 Back Up an Event Log 643
23.7 Create or Remove an Event Log 644
23.8 Write to an Event Log 646
23.9 Run a PowerShell Script for Windows Event Log Entries 646
23.10 Clear or Maintain an Event Log 648
23.11 Access Event Logs of a Remote Machine 650
24 Processes 653
24.1 List Currently Running Processes 654
24.2 Launch the Application Associated with a Document 655
24.3 Launch a Process 656
24.4 Stop a Process 658
24.5 Get the Owner of a Process 659
24.6 Get the Parent Process of a Process 660
24.7 Debug a Process 661
25 System Services 663
25.1 List All Running Services 663
25.2 Manage a Running Service 665
25.3 Configure a Service 666
26 Active Directory 669
26.1 Test Active Directory Scripts on a Local Installation 670
Table of Contents | xi
Trang 1426.2 Create an Organizational Unit 673
26.3 Get the Properties of an Organizational Unit 674
26.4 Modify Properties of an Organizational Unit 675
26.5 Delete an Organizational Unit 675
26.6 Get the Children of an Active Directory Container 676
26.7 Create a User Account 677
26.8 Program: Import Users in Bulk to Active Directory 678
26.9 Search for a User Account 680
26.10 Get and List the Properties of a User Account 681
26.11 Modify Properties of a User Account 682
26.12 Change a User Password 683
26.13 Create a Security or Distribution Group 683
26.14 Search for a Security or Distribution Group 685
26.15 Get the Properties of a Group 686
26.16 Find the Owner of a Group 687
26.17 Modify Properties of a Security or Distribution Group 688
26.18 Add a User to a Security or Distribution Group 688
26.19 Remove a User from a Security or Distribution Group 689
26.20 List a User’s Group Membership 690
26.21 List the Members of a Group 690
26.22 List the Users in an Organizational Unit 691
26.23 Search for a Computer Account 692
26.24 Get and List the Properties of a Computer Account 693
27 Enterprise Computer Management 695
27.1 Join a Computer to a Domain or Workgroup 695
27.2 Remove a Computer from a Domain 696
27.3 Rename a Computer 697
27.4 Program: List Logon or Logoff Scripts for a User 698
27.5 Program: List Startup or Shutdown Scripts for a Machine 699
27.6 Deploy PowerShell-Based Logon Scripts 701
27.7 Enable or Disable the Windows Firewall 702
27.8 Open or Close Ports in the Windows Firewall 702
27.9 Program: List All Installed Software 704
27.10 Uninstall an Application 705
27.11 Manage Computer Restore Points 706
27.12 Reboot or Shut Down a Computer 708
27.13 Determine Whether a Hotfix Is Installed 710
27.14 Manage Scheduled Tasks on a Computer 710
27.15 Retrieve Printer Information 714
27.16 Retrieve Printer Queue Statistics 715
27.17 Manage Printers and Print Queues 717
Trang 1527.18 Program: Summarize System Information 718
27.19 Renew a DHCP Lease 720
27.20 Assign a Static IP Address 721
27.21 List All IP Addresses for a Computer 723
27.22 List Network Adapter Properties 724
28 Windows Management Instrumentation 727
28.1 Access Windows Management Instrumentation and CIM Data 730
28.2 Modify the Properties of a WMI or CIM Instance 732
28.3 Invoke a Method on a WMI Instance or Class 734
28.4 Program: Determine Properties Available to WMI and CIM Filters 736
28.5 Program: Search for WMI Classes 737
28.6 Use NET to Perform Advanced WMI Tasks 740
28.7 Improve the Performance of Large-Scale WMI Operations 742
28.8 Convert a VBScript WMI Script to PowerShell 743
29 Remoting 749
29.1 Find Commands That Support Their Own Remoting 750
29.2 Enable PowerShell Remoting on a Computer 752
29.3 Interactively Manage a Remote Computer 754
29.4 Invoke a Command on a Remote Computer 756
29.5 Disconnect and Reconnect PowerShell Sessions 760
29.6 Program: Remotely Enable PowerShell Remoting 763
29.7 Program: Invoke a PowerShell Expression on a Remote Machine 765
29.8 Test Connectivity Between Two Computers 768
29.9 Limit Networking Scripts to Hosts That Respond 771
29.10 Enable Remote Desktop on a Computer 772
29.11 Configure User Permissions for Remoting 772
29.12 Enable Remoting to Workgroup Computers 774
29.13 Implicitly Invoke Commands from a Remote Computer 776
29.14 Create Sessions with Full Network Access 779
29.15 Pass Variables to Remote Sessions 783
29.16 Configure Advanced Remoting Quotas and Options 785
29.17 Invoke a Command on Many Computers 787
29.18 Run a Local Script on a Remote Computer 789
29.19 Program: Transfer a File to a Remote Computer 790
29.20 Determine Whether a Script Is Running on a Remote Computer 793
29.21 Create a Task-Specific Remoting Endpoint 794
30 Workflows 801
30.1 Write a Workflow 802
30.2 Run a Workflow 808
Table of Contents | xiii
Trang 1630.3 Suspend and Resume a Workflow 811
30.4 Invoke Islands of Traditional PowerShell Script 814
30.5 Invoke Workflow Actions in Parallel 816
30.6 Customize an Activity’s Connection Parameters 819
30.7 Write a Workflow That Requires Human Intervention 825
30.8 Add Raw XAML to a Workflow 827
30.9 Reference Custom Activities in a Workflow 828
30.10 Debug or Troubleshoot a Workflow 830
30.11 Use PowerShell Activities from a Traditional Windows Workflow Application 834
31 Transactions 837
31.1 Safely Experiment with Transactions 839
31.2 Change Error Recovery Behavior in Transactions 841
32 Event Handling 845
32.1 Respond to Automatically Generated Events 846
32.2 Create and Respond to Custom Events 849
32.3 Create a Temporary Event Subscription 852
32.4 Forward Events from a Remote Computer 853
32.5 Investigate Internal Event Action State 854
32.6 Use a Script Block as a NET Delegate or Event Handler 856
Part V References A PowerShell Language and Environment 861
B Regular Expression Reference 919
C XPath Quick Reference 929
D .NET String Formatting 933
E .NET DateTime Formatting 937
F Selected NET Classes and Their Uses 943
G WMI Reference 951
H Selected COM Objects and Their Uses 959
Trang 17I Selected Events and Their Uses 963
J Standard PowerShell Verbs 971 Index 975
Table of Contents | xv
Trang 19When Lee Holmes asked me to write the introduction to the third edition of his Windows
PowerShell Cookbook, I was deeply honored I have known Lee for a long time, and we
meet in real life every time I am out in Redmond, or when we happen to be speaking atthe same conference If you are like me, you already own the first two editions of thisgreat book You may even be asking yourself why you need a third edition of the samebook, and I will tell you: this is not the same book It is a completely revised book thattakes advantage of the significant changes we have made to both Windows PowerShell3.0 and to the underlying operating system
Consider this: Windows PowerShell 1.0 had 129 cmdlets, but Windows PowerShell 3.0
on Windows 8 has over 2,000 cmdlets and functions Because Lee’s book is so practical
in nature—it is, after all, a cookbook—this means that with so many more ingredients
to add to the recipes, the recipes will necessarily change In addition, with the newfunctionality comes additional opportunities for new recipes
More than just a cookbook, however, the third edition of the Windows PowerShellCookbook is also a textbook of how to write great Windows PowerShell scripts Just as
a budding saxophonist benefits from watching a legend such as Charlie Parker ply his
ax, so too does a budding scripter benefit from watching one of the guys who literally
wrote Windows PowerShell write scripts Each of these recipes is a perfectly crafted
example of a Windows PowerShell script—your task is to study these scripts so you can
go and do likewise
—Ed Wilson
Microsoft Scripting Guy and author of Windows Powershell 3.0
and Windows PowerShell 2.0 Best Practices
xvii
Trang 21In late 2002, Slashdot posted a story about a “next-generation shell” rumored to be indevelopment at Microsoft As a longtime fan of the power unlocked by shells and theirscripting languages, the post immediately captured my interest Could this shell providethe command-line power and productivity I’d long loved on Unix systems?
Since I had just joined Microsoft six months earlier, I jumped at the chance to finallyget to the bottom of a Slashdot-sourced Microsoft Mystery The post talked about strongintegration with the NET Framework, so I posted a query to an internal C# mailing list
I got a response that the project was called “Monad,” which I then used to track down
an internal prototype build
Prototype was a generous term In its early stages, the build was primarily a proof ofconcept Want to clear the screen? No problem! Just lean on the Enter key until yourprevious commands and output scroll out of view! But even at these early stages, it wasimmediately clear that Monad marked a revolution in command-line shells As withmany things of this magnitude, its beauty was self-evident Monad passed full-fidelity NET objects between its commands For even the most complex commands,Monad abolished the (until now, standard) need for fragile text-based parsing Simpleand powerful data manipulation tools supported this new model, creating a shell bothpowerful and easy to use
I joined the Monad development team shortly after that to help do my part to bring thismasterpiece of technology to the rest of the world Since then, Monad has grown tobecome a real, tangible product—now called Windows PowerShell
So why write a book about it? And why this book?
xix
Trang 22Many users have picked up PowerShell for the sake of learning PowerShell Any tangiblebenefits come by way of side effect Others, though, might prefer to opportunisticallylearn a new technology as it solves their needs How do you use PowerShell to navigatethe filesystem? How can you manage files and folders? Retrieve a web page?
This book focuses squarely on helping you learn PowerShell through task-based solu‐tions to your most pressing problems Read a recipe, read a chapter, or read the entirebook—regardless, you’re bound to learn something
Who This Book Is For
This book helps you use PowerShell to get things done It contains hundreds of solutions
to specific, real-world problems For systems management, you’ll find plenty of exam‐ples that show how to manage the filesystem, the Windows Registry, event logs, pro‐cesses, and more For enterprise administration, you’ll find two entire chapters devoted
to WMI, Active Directory, and other enterprise-focused tasks
Along the way, you’ll also learn an enormous amount about PowerShell: its features, itscommands, and its scripting language—but most importantly you’ll solve problems
How This Book Is Organized
This book consists of five main sections: a guided tour of PowerShell, PowerShell fun‐damentals, common tasks, administrator tasks, and a detailed reference
• A razor-sharp focus on administrators
• A consistent model for learning and discovery
• Ubiquitous scripting
• Integration with critical management technologies
• A consistent model for interacting with data stores
The tour helps you become familiar with PowerShell as a whole This familiarity willcreate a mental framework for you to understand the solutions from the rest of the book
Trang 23Part II: Fundamentals
Chapters 1 through 8 cover the fundamentals that underpin the solutions in this book.This section introduces you to the PowerShell interactive shell, fundamental pipelineand object concepts, and many features of the PowerShell scripting language
Part III: Common Tasks
Chapters 9 through 19 cover the tasks you will run into most commonly when starting
to tackle more complex problems in PowerShell This includes working with simple andstructured files, Internet-connected scripts, code reuse, user interaction, and more
Part IV: Administrator Tasks
Chapters 20 through 32 focus on the most common tasks in systems and enterprisemanagement Chapters 20 through 25 focus on individual systems: the filesystem, theregistry, event logs, processes, services, and more Chapters 26 and 27 focus on ActiveDirectory, as well as the typical tasks most common in managing networked or domain-joined systems Chapters 28 through 30 focus on the three crucial facets of robust multi-machine management: WMI, PowerShell Remoting, and PowerShell Workflows
Part V: References
Many books belch useless information into their appendixes simply to increase pagecount In this book, however, the detailed references underpin an integral and essentialresource for learning and using PowerShell The appendixes cover:
• The PowerShell language and environment
• Regular expression syntax and PowerShell-focused examples
• XPath quick reference
• NET string formatting syntax and PowerShell-focused examples
• NET DateTime formatting syntax and PowerShell-focused examples
• Administrator-friendly NET classes and their uses
• Administrator-friendly WMI classes and their uses
• Administrator-friendly COM objects and their uses
• Selected events and their uses
• PowerShell’s standard verbs
Preface | xxi
Trang 24What You Need to Use This Book
The majority of this book requires only a working installation of Windows PowerShell.Windows 7, Windows 8, Windows Server 2008 R2, and Windows Server 2012 includeWindows PowerShell by default If you do not yet have PowerShell installed, you mayobtain it by following the download link here This link provides download instructionsfor PowerShell on Windows XP, Windows Server 2003, and Windows Vista For WindowsServer 2008, PowerShell comes installed as an optional component that you can enablethrough the Control Panel like other optional components
The Active Directory scripts given in Chapter 26 are most useful when applied to anenterprise environment, but Recipe 26.1, “Test Active Directory Scripts on a Local In‐stallation” shows how to install additional software (Active Directory Lightweight Di‐rectory Services, or Active Directory Application Mode) that lets you run these scriptsagainst a local installation
Conventions Used in This Book
The following typographical conventions are used in this book:
Constant width bold
Shows commands or other text that should be typed literally by the user
Constant width italic
Shows text that should be replaced with user-supplied values
This icon signifies a tip, suggestion, or general note
This icon indicates a warning or caution
Trang 25Code Examples
Obtaining Code Examples
To obtain electronic versions of the programs and examples given in this book, visit the
Examples link here
Using Code Examples
This book is here to help you get your job done In general, you may use the code in thisbook in your programs and documentation You do not need to contact us for permis‐sion unless you’re reproducing a significant portion of the code For example, writing aprogram that uses several chunks of code from this book does not require permission
Selling or distributing a CD-ROM of examples from O’Reilly books does require per‐
mission Answering a question by citing this book and quoting example code does notrequire permission Incorporating a significant amount of example code from this book
into your product’s documentation does require permission.
We appreciate, but do not require, attribution An attribution usually includes the title,
author, publisher, and ISBN For example: “Windows PowerShell Cookbook, Third Edi‐
tion, by Lee Holmes (O’Reilly) Copyright 2013 Lee Holmes, 978-1-449-32068-3.”
If you feel your use of code examples falls outside fair use or the permission given, feelfree to contact us at permissions@oreilly.com
Safari® Books Online
Safari Books Online (www.safaribooksonline.com) is an on-demanddigital library that delivers expert content in both book and videoform from the world’s leading authors in technology and business.Technology professionals, software developers, web designers, and business and creativeprofessionals use Safari Books Online as their primary resource for research, problemsolving, learning, and certification training
Safari Books Online offers a range of product mixes and pricing programs for organi‐zations, government agencies, and individuals Subscribers have access to thousands ofbooks, training videos, and prepublication manuscripts in one fully searchable databasefrom publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, JohnWiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FTPress, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐ogy, and dozens more For more information about Safari Books Online, please visit us
online
Preface | xxiii
Trang 26Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Writing is the task of crafting icebergs The heft of the book you hold in your hands isjust a hint of the multiyear, multirelease effort it took to get it there And by a cast muchlarger than me
The groundwork started decades ago My parents nurtured my interest in computersand software, supported an evening-only bulletin board service, put up with “viruses”that told them to buy a new computer for Christmas, and even listened to me blatherabout batch files or how PowerShell compares to Excel Without their support, whoknows where I’d be
My family and friends have helped keep me sane for two editions of the book now Ariel:you are the light of my life Robin: thinking of you reminds me each day that serendipity
is still alive and well in this busy world Thank you to all of my friends and family forbeing there for me You can have me back now :)
I would not have written either edition of this book without the tremendous influence
of Guy Allen, visionary of the University of Toronto’s Professional Writing program.Guy: your mentoring forever changed me, just as it molds thousands of others fromEnglish hackers into writers
Trang 27Of course, members of the PowerShell team (both new and old) are the ones that madethis a book about PowerShell Building this product with you has been a unique challengeand experience—but most of all, a distinct pleasure In addition to the PowerShell team,the entire PowerShell community defined this book’s focus From MVPs to early adopt‐ers to newsgroup lurkers: your support, questions, and feedback have been the inspi‐ration behind each page.
Converting thoughts into print always involves a cast of unsung heroes, even thougheach author tries his best to convince the world how important these heroes are.Thank you to the many technical reviewers who participated in O’Reilly’s Open Feed‐back Publishing System, especially Aleksandar Nikolic and Shay Levy I truly appreciateyou donating your nights and weekends to help craft something of which we can all beproud
To the awesome staff at O’Reilly—Rachel Roumeliotis, Kara Ebrahim, Mike Hendrick‐son, Genevieve d’Entremont, Teresa Elsey, Laurel Ruma, the O’Reilly Tools Monks, andthe production team—your patience and persistence helped craft a book that holds true
to its original vision You also ensured that the book didn’t just knock around in myhead but actually got out the door
This book would not have been possible without the support from each and every one
of you
Preface | xxv
Trang 29PART I
Tour
Trang 31A Guided Tour of Windows PowerShell
Introduction
Windows PowerShell promises to revolutionize the world of system management andcommand-line shells From its object-based pipelines to its administrator focus to itsenormous reach into other Microsoft management technologies, PowerShell drasticallyimproves the productivity of administrators and power users alike
When you’re learning a new technology, it is natural to feel bewildered at first by all theunfamiliar features and functionality This perhaps rings especially true for users new
to Windows PowerShell because it may be their first experience with a fully featuredcommand-line shell Or worse, they’ve heard stories of PowerShell’s fantastic integratedscripting capabilities and fear being forced into a world of programming that they’veactively avoided until now
Fortunately, these fears are entirely misguided; PowerShell is a shell that both grows withyou and grows on you Let’s take a tour to see what it is capable of:
• PowerShell works with standard Windows commands and applications You don’thave to throw away what you already know and use
• PowerShell introduces a powerful new type of command PowerShell commands
(called cmdlets) share a common Verb-Noun syntax and offer many usability im‐
provements over standard commands
• PowerShell understands objects Working directly with richly structured objectsmakes working with (and combining) PowerShell commands immensely easierthan working in the plain-text world of traditional shells
3
Trang 32• PowerShell caters to administrators Even with all its advances, PowerShell focusesstrongly on its use as an interactive shell: the experience of entering commands in
a running PowerShell application
• PowerShell supports discovery Using three simple commands, you can learn anddiscover almost anything PowerShell has to offer
• PowerShell enables ubiquitous scripting With a fully fledged scripting languagethat works directly from the command line, PowerShell lets you automate tasks withease
• PowerShell bridges many technologies By letting you work with NET, COM, WMI,XML, and Active Directory, PowerShell makes working with these previously iso‐lated technologies easier than ever before
• PowerShell simplifies management of data stores Through its provider model,PowerShell lets you manage data stores using the same techniques you already use
to manage files and folders
We’ll explore each of these pillars in this introductory tour of PowerShell If you arerunning Windows 7 (or later) or Windows 2008 R2 (or later), PowerShell is alreadyinstalled If not, visit the download link here to install it PowerShell and its supporting
technologies are together referred to as the Windows Management Framework.
An Interactive Shell
At its core, PowerShell is first and foremost an interactive shell While it supports script‐ing and other powerful features, its focus as a shell underpins everything
Getting started in PowerShell is a simple matter of launching PowerShell.exe rather than
cmd.exe—the shells begin to diverge as you explore the intermediate and advanced
functionality, but you can be productive in PowerShell immediately
To launch Windows PowerShell, do one of the following:
• Click Start→All Programs→Accessories→Windows PowerShell
• Click Start→Run, and then type PowerShell.
A PowerShell prompt window opens that’s nearly identical to the traditional commandprompt window of Windows XP, Windows Server 2003, and their many ancestors The
PS C:\Users\Lee> prompt indicates that PowerShell is ready for input, as shown in
Figure I-1
Trang 33Figure I-1 Windows PowerShell, ready for input
Once you’ve launched your PowerShell prompt, you can enter DOS-style and Unix-stylecommands to navigate around the filesystem just as you would with any Windows orUnix command prompt—as in the interactive session shown in Example I-1 In thisexample, we use the pushd, cd, dir, pwd, and popd commands to store the current lo‐cation, navigate around the filesystem, list items in the current directory, and then return
to the original location Try it!
Example I-1 Entering many standard DOS- and Unix-style file manipulation com‐ mands produces the same results you get when you use them with any other Windows shell
PS C:\Documents and Settings\Lee> function Prompt { "PS > " }
d 10/7/2006 4:30 PM Documents and Settings
A Guided Tour of Windows PowerShell | 5
Trang 34In this example, our first command customizes the prompt In cmd.exe, customizing
the prompt looks like prompt $P$G In bash, it looks like PS1="[\h] \w> " In Power‐Shell, you define a function that returns whatever you want displayed Recipe 11.2,
“Write a Function” introduces functions and how to write them
The pushd command is an alternative name (alias) to the much more descriptivelynamed PowerShell command Push-Location Likewise, the cd, dir, popd, and pwdcommands all have more memorable counterparts
Although navigating around the filesystem is helpful, so is running the tools you knowand love, such as ipconfig and notepad Type the command name and you’ll see resultslike those shown in Example I-2
Example I-2 Windows tools and applications such as ipconfig run in PowerShell just as they do in cmd.exe
PS > ipconfig
Windows IP Configuration
Ethernet adapter Wireless Network Connection 4:
Connection-specific DNS Suffix : hsd1.wa.comcast.net.
Trang 35Entering ipconfig displays the IP addresses of your current network connections En‐tering notepad runs—as you’d expect—the Notepad editor that ships with Windows.Try them both on your own machine.
Structured Commands (Cmdlets)
In addition to supporting traditional Windows executables, PowerShell introduces a
powerful new type of command called a cmdlet (pronounced “command-let”) All cmdlets are named in a Verb-Noun pattern, such as Get-Process, Get-Content, and
Stop-Process
PS > Get-Process -Name lsass
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
- - - - - -
668 13 6228 1660 46 932 lsass
In this example, you provide a value to the ProcessName parameter to get a specificprocess by name
Once you know the handful of common verbs in PowerShell, learning
how to work with new nouns becomes much easier While you may
never have worked with a certain object before (such as a Service), the
standard Get, Set, Start, and Stop actions still apply For a list of these
common verbs, see Table J-1 in Appendix J
You don’t always have to type these full cmdlet names, however PowerShell lets you usethe Tab key to autocomplete cmdlet names and parameter names:
PS > Get-Pr<TAB> -N<TAB> lsass
For quick interactive use, even that may be too much typing To help improve yourefficiency, PowerShell defines aliases for all common commands and lets you defineyour own In addition to alias names, PowerShell requires only that you type enough ofthe parameter name to disambiguate it from the rest of the parameters in that cmdlet.PowerShell is also case-insensitive Using the built-in gps alias (which represents theGet-Process cmdlet) along with parameter shortening, you can instead type:
PS > gps -n lsass
Going even further, PowerShell supports positional parameters on cmdlets Positional
parameters let you provide parameter values in a certain position on the command line,rather than having to specify them by name The Get-Process cmdlet takes a processname as its first positional parameter This parameter even supports wildcards:
PS > gps l*s
A Guided Tour of Windows PowerShell | 7
Trang 36Deep Integration of Objects
PowerShell begins to flex more of its muscle as you explore the way it handles structureddata and richly functional objects For example, the following command generates asimple text string Since nothing captures that output, PowerShell displays it to you:
PS > "Hello World"
Hello World
The string you just generated is, in fact, a fully functional object from the NET Frame‐work For example, you can access its Length property, which tells you how many char‐acters are in the string To access a property, you place a dot between the object and itsproperty name:
PS > "Hello World".Length
11
All PowerShell commands that produce output generate that output as objects as well.For example, the Get-Process cmdlet generates a System.Diagnostics.Process ob‐ject, which you can store in a variable In PowerShell, variable names start with a $character If you have an instance of Notepad running, the following command stores
a reference to it:
$process = Get-Process notepad
Since this is a fully functional Process object from the NET Framework, you can callmethods on that object to perform actions on it This command calls the Kill() method,which stops a process To access a method, you place a dot between the object and itsmethod name:
$process.Kill()
PowerShell supports this functionality more directly through the Stop-Process cmdlet,but this example demonstrates an important point about your ability to interact withthese rich objects
Administrators as First-Class Users
While PowerShell’s support for objects from the NET Framework quickens the pulse
of most users, PowerShell continues to focus strongly on administrative tasks For ex‐ample, PowerShell supports MB (for megabyte) and GB (for gigabyte) as some of its stan‐dard administrative constants For example, how many disks will it take to back up a 40
GB hard drive to CD-ROM?
PS > 40GB / 650MB
63.0153846153846
Trang 37Although the NET Framework is traditionally a development platform, it contains awealth of functionality useful for administrators too! In fact, it makes PowerShell a greatcalendar For example, is 2008 a leap year? PowerShell can tell you:
PS > [DateTime]::IsLeapYear(2008)
True
Going further, how might you determine how much time remains until summer? Thefollowing command converts "06/21/2011" (the start of summer) to a date, and thensubtracts the current date from that It stores the result in the $result variable, and thenaccesses the TotalDays property
PS > $result = [DateTime] "06/21/2011" - [DateTime]::Now
PS > $result.TotalDays
283.0549285662616
Composable Commands
Whenever a command generates output, you can use a pipeline character (|) to pass that
output directly to another command as input If the second command understands theobjects produced by the first command, it can operate on the results You can chaintogether many commands this way, creating powerful compositions out of a few simple
operations For example, the following command gets all items in the Path1 directory and moves them to the Path2 directory:
Get-Item Path1\* | Move-Item -Destination Path2
You can create even more complex commands by adding additional cmdlets to thepipeline In Example I-3, the first command gets all processes running on the system
It passes those to the Where-Object cmdlet, which runs a comparison against eachincoming item In this case, the comparison is $_.Handles -ge 500, which checkswhether the Handles property of the current object (represented by the $_ variable) isgreater than or equal to 500 For each object in which this comparison holds true, youpass the results to the Sort-Object cmdlet, asking it to sort items by their Handlesproperty Finally, you pass the objects to the Format-Table cmdlet to generate a tablethat contains the Handles, Name, and Description of the process
Example I-3 You can build more complex PowerShell commands by using pipelines to link cmdlets, as shown here with Get-Process, Where-Object, Sort-Object, and Format- Table
PS > Get-Process |
Where-Object { $_.Handles -ge 500 } |
Sort-Object Handles |
Format-Table Handles,Name,Description -Auto
A Guided Tour of Windows PowerShell | 9
Trang 38Handles Name Description
964 WINWORD Microsoft Office Word
1112 OUTLOOK Microsoft Office Outlook
2063 svchost
Techniques to Protect You from Yourself
While aliases, wildcards, and composable pipelines are powerful, their use in commandsthat modify system information can easily be nerve-racking After all, what does thiscommand do? Think about it, but don’t try it just yet:
PS > gps [b-t]*[c-r] | Stop-Process
It appears to stop all processes that begin with the letters b through t and end with theletters c through r How can you be sure? Let PowerShell tell you For commands thatmodify data, PowerShell supports -WhatIf and -Confirm parameters that let you see
what a command would do:
PS > gps [b-t]*[c-r] | Stop-Process -whatif
What if: Performing operation "Stop-Process" on Target "ctfmon (812)".
What if: Performing operation "Stop-Process" on Target "Ditto (1916)".
What if: Performing operation "Stop-Process" on Target "dsamain (316)".
What if: Performing operation "Stop-Process" on Target "ehrecvr (1832)".
What if: Performing operation "Stop-Process" on Target "ehSched (1852)".
What if: Performing operation "Stop-Process" on Target "EXCEL (2092)".
What if: Performing operation "Stop-Process" on Target "explorer (1900)" ( )
In this interaction, using the -WhatIf parameter with the Stop-Process pipelined com‐mand lets you preview which processes on your system will be stopped before youactually carry out the operation
Note that this example is not a dare! In the words of one reviewer:
Not only did it stop everything, but on Vista, it forced a shutdown with only one minute warning!
It was very funny though…At least I had enough time to save everything first!
Trang 39Common Discovery Commands
While reading through a guided tour is helpful, I find that most learning happens in an
ad hoc fashion To find all commands that match a given wildcard, use the Get-Commandcmdlet For example, by entering the following, you can find out which PowerShell
commands (and Windows applications) contain the word process.
PS > Get-Command *process*
CommandType Name Definition
-
-Cmdlet Get-Process Get-Process [[-Name] <Str
Application qprocess.exe c:\windows\system32\qproc
Cmdlet Stop-Process Stop-Process [-Id] <Int32
To see what a command such as Get-Process does, use the Get-Help cmdlet, like this:
PS > Get-Help Get-Process
Since PowerShell lets you work with objects from the NET Framework, it provides theGet-Member cmdlet to retrieve information about the properties and methods that anobject, such as a NET System.String, supports Piping a string to the Get-Membercommand displays its type name and its members:
PS > "Hello World" | Get-Member
ToString Method System.String ToString(), System ToUpper Method System.String ToUpper(), System ToUpperInvariant Method System.String ToUpperInvariant()
Trim Method System.String Trim(Params Char[] TrimEnd Method System.String TrimEnd(Params Cha TrimStart Method System.String TrimStart(Params C Chars ParameterizedProperty System.Char Chars(Int32 index) { Length Property System.Int32 Length {get;}
A Guided Tour of Windows PowerShell | 11
Trang 40Ubiquitous Scripting
PowerShell makes no distinction between the commands typed at the command lineand the commands written in a script Your favorite cmdlets work in scripts and yourfavorite scripting techniques (e.g., the foreach statement) work directly on the com‐mand line For example, to add up the handle count for all running processes:
In addition to using PowerShell scripting keywords, you can also create and work di‐rectly with objects from the NET Framework that you may be familiar with PowerShellbecomes almost like the C# immediate mode in Visual Studio Example I-4 shows howPowerShell lets you easily interact with the NET Framework
Example I-4 Using objects from the NET Framework to retrieve a web page and process its content
PS > $webClient = New-Object System.Net.WebClient
PS > $content = $webClient.DownloadString(
"http://blogs.msdn.com/PowerShell/rss.aspx")
PS > $content.Substring(0,1000)
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedS
tylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://pu
PS > Get-History | Foreach-Object { $_.CommandLine } > c:\temp\script.ps1
PS > notepad c:\temp\script.ps1
(save the content you want to keep)
PS > c:\temp\script.ps1