Windows PowerShell Cookbook Lee Holmes O'REILLY' Beijing Cambridge Farnham Koln Paris Sebastopol Taipei Tokyo
Table of Contents Foreword Preface xvii xxi Part I. Tour A Guided Tour of Windows PowerShell 3 Introduction 3 An Interactive Shell 4 Structured Commands (Cmdlets) 6 Deep Integration of Objects " 7 Administrators As First-Class Users 8 Composable Commands. 9 Techniques to Protect You from Yourself 9 Common Discovery Commands ' 10 Ubiquitous Scripting 11 Ad Hoc Development 12 Bridging Technologies 12 Namespace Navigation Through Providers 14 Much, Much More 9 16 Part II. Fundamentals 1. The Windows PowerShell Interactive Shell 19 1.0 Introduction 19 1.1 Run Programs, Scripts, and Existing Tools 19 1.2 Run a PowerShell Command 21
1.3 Customize Your Shell, Profile, and Prompt 22 1.4 Find a Command to Accomplish a Task 25 1.5 Get Help on a Command 26 1.6 Program: Search Help for Text 28 1.7 Invoke a PowerShell Script From Outside PowerShell 29 1.8 Program: Retain Changes to Environment Variables Set by a Batch File30 1.9 Get the System Date and Time 32 1.10 Determine the Status of the Last Command 33 1.11 Measure the Duration of a Command 34 1.12 Customize the Shell to Improve Your Productivity 35 1.13 Program: Learn Aliases for Common Commands 36 1.14 Access and Manage Your Console History 38 1.15 Store the Output of a Command into a File 39 1.16 Add Information to the End of a File 41 1.17 Record a Transcript of Your Shell Session 41 1.18 Display the Properties of an Item As a List 42 1.19 Display the Properties of an Item As a Table 42 1.20 Manage the Error Output of Commands 44 1.21 Configure Debug, Verbose, and Progress Output 45 1.22 Extend Your Shell with Additional Snapins 47 1.23 Use Console Files to Load and Save Sets of Snapins 48 2. Pipelines *. 49 2.0 Introduction 49 2.1 Filter Items in a List or Command Output 50 2.2 Program: Simplify Most Where-Object Filters 51 2.3 Program: Interactively Filter Lists of Objects 52 2.4 Work with Each Item in a List or Command Output 54 2.5 Automate Data-Intensive Tasks. 56 3. Variables and Objects 61 3.0 Introduction 61 3.1 Store Information in Variables 62 3.2 Access Environment Variables 63 3.3 Control Access and Scope of Variables and Other Items 65 3.4 Work with.net Objects 67 3.5 Create an Instance of a.net Object 71 3.6 Program: Create Instances of Generic Objects 73 3.7 Reduce Typing for Long Class Names 74 Table of Contents
3.8 Use a COM Object 76 3.9 Learn About Types and Objects 77 3.10 Get Detailed Documentation About Types and Objects 78 3.11 Add Custom Methods and Properties to Objects 80 3.12 Add Custom Methods and Properties to Types 82 4. Looping and Flow Control 87 4.0 Introduction 87 4.1 Make Decisions with Comparison and Logical Operators 87 4.2 Adjust Script Flow Using Conditional Statements 89 4.3 Manage Large Conditional Statements with Switches 90 4.4 Repeat Operations with Loops 91 4.5 Add a Pause or Delay 93 5. Strings and Unstructured Text.. 95 5.0 Introduction 95 5.1 Create a String 95 5.2 Create a Multiline or Formatted String 97 5.3 Place Special Characters in a String 98 5.4 Insert Dynamic Information in a String ' 99 5.5 Prevent a String from Including Dynamic Information 100 5.6 Place Formatted Information in a String 101 5.7 Search a6tring for Text or a Pattern 102 5.8 Replace Text in a String 105 5.9 Convert a String to Upper/Lowercase 106 5.10 Trim a String ' ", 107 5.11 Format a Date for Output^ ' 108 5.12 Program: Convert Text Streams to Objects 110 5.13 Generate Large Reports'and Text Streams 114 6. Calculations and Math 117 6.0 Introduction 117 6.1 Perform Simple Arithmetic * 117 6.2 Perform Complex Arithmetic 119 6.3 Measure Statistical Properties of a List 121 6.4 Work with Numbers As Binary 123 6.5 Simplify Math with Administrative Constants 127 6.6 Convert Numbers Between Bases 128 Table of Contents I vii
Part III. Common Tasks 7. Simple Files 133 7.0 Introduction 133 7.1 Get the Content of a File 133 7.2 Search a File for Text or a Pattern 135 7.3 Parse and Manage Text-Based Logfiles 136 7.4 Parse and Manage Binary Files 139 7.5 Create a Temporary File 141 7.6 Search and Replace Text in a File 143 8. Structured Files 147 8.0 Introduction 147 8.1 Access Information in an XML File 147 8.2 Perform an XPath Query Against an XML File 150 8.3 Modify Data in an XML File 151 8.4 Easily Import and Export Your Structured Data 153 8.5 Store the Output of a Command in a CSV File 155 8.6 Import Structured Data from a CSV File 156 8.7 Use Excel to Manage Command Output 157 9. Internet-Enabled Scrjpts 160 9.0 Introduction 160 9.1 Download a File from the Internet 160 9.2 Download a Web Pa'ge from the Internet 161 9.3 Program: Get-PageUrls -' 163 ; 9.4 Program: Connect-WebService. 166 9.5 Export Command Output As^a Web Page 170 9.6 Program: Send an Email " 170 9.7 Program: Interact with Internet Protocols 172 10. Code Reuse r. 176 10.0 Introduction 176 10.1 Write a Script 176 10.2 Write a Function 179 10.3 Write a Script Block 180 10.4 Return Data from a Script, Function, or Script Block 182 10.5 Place Common Functions in a Library 184 10.6 Access Arguments of a Script, Function, or Script Block 185 viii I Table of Contents
10.7 Access Pipeline Input 188 10.8 Write Pipeline-Oriented Scripts with Cmdlet Keywords 189 10.9 Write a Pipeline-Oriented Function 193 11. Lists, Arrays, and Hashtables 195 11.0 Introduction 195 11.1 Create an Array or List of Items 195 11.2 Create a Jagged or Multidimensional Array, 197 11.3 Access Elements of an Array 198 11.4 Visit Each Element of an Array 199 11.5 Sort an Array or List of Items 200 11.6 Determine Whether an Array Contains an Item 200 11.7 Combine Two Arrays 201 11.8 Find Items in an Array That Match a Value 202 11.9 Remove Elements from an Array 203 11.10 Find Items in an Array Greater or Less Than a Value 204 11.11 Use the ArrayList Class for Advanced Array Tasks 205 11.12 Create a Hashtable or Associative Array 206 11.13 Sort a Hashtable by Key or Value 207 12. User Interaction 209 12.0 Introduction 209 12.1 Read a Line of User Input 209 12.2 Read a Key of User Input 210 12.3 Program: Display a Menu to the User 211 12.4 Display Messages and Output to,the User 213 12.5 Provide Progress Updates on Long-Running Tasks 216 12.6 Write Culture-Aware Scripts'. 217 12.7 Program: Invoke a Script Block with Alternate Culture Settings 220 12.8 Access Features of the Host's User Interface 221 12.9 Program: Add a Graphical User Interface to Your Script 223 13. Tracing and Error Management T. 226 13.0 Introduction 226 13.1 View the Errors Generated by a Command 226 13.2 Handle Warnings, Errors, and Terminating Errors 228 13.3 Output Warnings, Errors, and Terminating Errors 230 13.4 Debug a Script 231 13.5 Collect Detailed Traces of a Script or Command 234 13.6 Program: Analyze a Script's Performance Profile 234 Table of Contents ix
14. Environmental Awareness 240 14.0 Introduction ' 240 14.1 View and Modify Environment Variables 240 14.2 Access Information About Your Command's Invocation 242 14.3 Program: Investigate the Invocationlnfo Variable 244 14.4 Find Your Script's Name 246 14.5 Find Your Script's Location 247 14.6 Find the Location of Common System Paths 248 14.7 Program: Search the Windows Start Menu 250 14.8 Get the Current Location 252 14.9 Safely Build File Paths Out of Their Components 253 14.10 Interact with PowerShell's Global Environment 254 15. Extend the Reach of Windows PowerShell 255 15.0 Introduction 255 15.1 Access Windows Management Instrumentation Data 255 15.2 Program: Determine Properties Available to WMI Filters 257 15.3 Program: Search for WMI Classes 258 15.4 Use.NET to Perform Advanced WMI Tasks 261 15.5 Convert a VBScript WMI Script to PowerShell 263 15.6 Automate Programs Using COM Scripting Interfaces 266 15.7 Program: Query a SQL Data Source 267 15.8 Access Windows Performance Counters 270 15.9 Program: Invoke Native Windows API Calls 271 15.10 Program: Add Inline C# to Your PowerShell Script 273 15.11 Access a.net SDK Library / 276 15.12 Create Your Own PowerShell Cfndlet 279 15.13 Add PowerShell Scripting to Your Own Program 283 16. Security and Script Signing 286 16.0 Introduction 286 16.1 Enable Scripting Through an Execution Policy 287 16.2 Sign a PowerShell Script or Formatting File 289 16.3 Program: Create a Self-Signed Certificate 291 16.4 Manage PowerShell Security in an Enterprise 292 16.5 Verify the Digital Signature of a PowerShell Script 295 16.6 Securely Handle Sensitive Information 296 16.7 Securely Request Usernames and Passwords 298 16.8 Program: Start a Process As Another User 300 x Table of Contents
16.9 Securely Store Credentials on Disk 301 16.10 Access User and Machine Certificates 303 16.11 Program: Search the Certificate Store 304 Part IV. Administrator Tasks 17. FilesandDirectories 309 17.0 Introduction. 309 17.1 Find All Files Modified Before a Certain Date 310 17.2 Clear or Remove a File 311 17.3 Manage and Change the Attributes of a File 312 17.4 Get the Files in a Directory 313 17.5 Find Files That Match a Pattern 314 17.6 Manage Files That Include Special Characters 317 17.7 Program: Get Disk Usage Information 318 17.8 Determine the Current Location 320 17.9 Monitor a File for Changes 321 17.10 Program: Get the MD5 or SHA1 Hash of a File 321 17.11 Create a Directory 324 17.12 Remove a File or Directory 324 17.13 Rename a File or Directory 325 17.14 Move a File or Directory 326 17.15 Get the ACL of a File or Directory. 327 17.16 Set the ACL of a File or Directory 329 17.17 Program: Add Extended File Properties to Files 330 17.18 Program: Create a FilesystenrHard Link 332 17.19 Program: Create a ZIP Archive 334 18. The Windows Registry 336 18.0 Introduction 336 18.1 Navigate the Registry 336 18.2 View a Registry Key " 337 18.3 Modify or Remove a Registry Key Value 338 18.4 Create a Registry Key Value 339 18.5 Remove a Registry Key 340 18.6 Add a Site to an Internet Explorer Security Zone 341 18.7 Modify Internet Explorer Settings 343 18.8 Program: Search the Windows Registry 344 Table of Contents xi
18.9 Get the ACL of a Registry Key 346 18.10 Set the ACL of a Registry Key 347 18.11 Work with the Registry of a Remote Computer 348 18.12 Program: Get Registry Items from Remote Machines 349 18.13 Program: Get Properties of Remote Registry Keys 351 18.14 Program: Set Properties of Remote Registry Keys 353 18.15 Discover Registry Settings for Programs 354 19. Comparing Data 358 19.0 Introduction 358 19.1 Compare the Output of Two Commands 358 19.2 Determine the Differences Between Two Files 359 19.3 Verify Integrity of File Sets 360 20. Event Logs 362 20.0 Introduction 362 20.1 List All Event Logs 362 20.2 Get the Newest Entries from an Event Log 363 20.3 Find Event Log Entries with Specific Text 364 20.4 Retrieve a Specific Event Log Entry 365 20.5 Find Event Log Entries by Their Frequency 367 20.6 Back Up an Event Log 369 20.7 Create or Remove an Event Log 369 20.8 Write to an Event Log 370 20.9 Access Event Logs of a Remote Machine 371 21. Processes ^-r 373 21.0 Introduction ' - 373 21.1 List Currently Running Processes 373 21.2 Launch a Process 375 21.3 Stop a Process 376 21.4 Program: Invoke a PowerShell Expression on a Remote Machine 377 22. System Services 380 22.0 Introduction 380 22.1 List All Running Services 380 22.2 Manage a Running Service 382 22.3 Access Services on a Remote Machine 383 xii I Table of Contents
23. Active Directory 385 23.0 Introduction 385 23.1 Test Active Directory Scripts on a Local Installation 385 23.2 Create an Organizational Unit 388 23.3 Get the Properties of an Organizational Unit 388 23.4 Modify Properties of an Organizational Unit 389 23.5 Get the Children of an Active Directory Container 390 23.6 Create a User Account 390 23.7 Program: Import Users in Bulk to Active Directory 391 23.8 Search for a User Account 393 23.9 Get and List the Properties of a User Account 394 23.10 Modify Properties of a User Account 395 23.11 Create a Security or Distribution Group 395 23.12 Search for a Security or Distribution Group 396 23.13 Get the Properties of a Group 397 23.14 Find the Owner of a Group 398 23.15 Modify Properties of a Security or Distribution Group 399 23.16 Add a User to a Security or Distribution Group 399 23.17 Remove a User from a Security or Distribution Group 400 23.18 List a User's Group Membership 400 23.19 List the Members of a Group, 401 23.20 List the Users in an Organizational Unit 401 23.21 Search for a Computer Account. 402 23.22 Get and List the Properties of a Computer Account 403 24. Enterprise Computer Management. / 405 24.0 Introduction ; ' '' 405 24.1 Program: List Logon or Logoff Scripts for a User 405 24.2 Program: List Startup or Shutdown Scripts for a Machine 407 24.3 Enable or Disable the Windows Firewall 408 24.4 Open or Close Ports in the Windows Firewall 409 24.5 Program: List All Installed Software^ 410 24.6 Uninstall an Application 411 24.7 Manage Scheduled Tasks on a Computer 412 24.8 Retrieve Printer Information 413 24.9 Retrieve Printer Queue Statistics 414 24.10 Manage Printers and Print Queues 416 24.11 Determine Whether a Hotfix Is Installed 417 24.12 Program: Summarize System Information 419 Table of Contents I xiii
< 24.13 Renew a DHCP Lease 420 24.14 Assign a Static IP Address. 421 24.15 List All IP Addresses for a Computer 423 24.16 List Network Adapter Properties 424 25. Manage an Exchange 2007 Server 426 25.0 Introduction 426 25.1 Experiment with Exchange Management Shell 427 25.2 Automate Wizard-Guided Tasks 427 25.3 Manage Exchange Users 428 25.4 Manage Mailboxes 430 25.5 Manage Distribution Groups 431 25.6 Manage Transport Rules, 431 25.7 Manage Outlook Web Access 432 26. Manage an Operations Manager 2007 Server 434 26.0 Introduction 434 26.1 Experiment with the Command Shell 434 26.2 Manage Operations Manager Agents 435 26.3 Schedule a Maintenance Window 436 26.4 Get, Install, and Uninstall Management Packs 437 26.5 Enable or Disable Rules 438 26.6 List and Start Tasks - 439 26.7 Manage Alerts 439 PartV. References A. PowerShell Language and Environment 443 Commands and Expressions - 443 Comments 444 Variables 444 Booleans * 446 Strings 446 Numbers 448 Arrays and Lists 449 Hashtables (Associative Arrays) 451 XML 452 Simple Opera'tors 453 xiv I Table of Contents
Comparison Operators 458 Conditional Statements 460 Looping Statements 464 Working with the.net Framework 467 Writing Scripts, Reusing Functionality 473 Managing Errors 478 Formatting Output 480 Capturing Output 482 Tracing and Debugging 482 Common Customization Points 484 B. Regular Expression Reference 488 C. PowerShell Automatic Variables 496 D. Standard PowerShell Verbs 499 E. Selected.NET Classes and Their Uses 502 F. WMI Reference 509 G. Selected COM Objects and Their Uses 516 H..NET String Formatting 519 Standard Numeric Format Strings 519 Custom Numeric Format Strings 520 I..NET DateTime Formatting.'". >. 522 Index '.' 529 Table of Contents I xv