Synopses & Reviews
This Cookbook by Windows PowerShell team developer Lee Holmes provides hundreds of tested scripts that you can use right away to get Microsoft's new tool working for you. More than 150 recipes, combined with a concise task-based introduction to the Windows PowerShell scripting language and environment, make it the perfect look-up guide when you encounter a thorny problem, or need a quick solution. The ideal companion to any tutorial or reference, this book meets the needs of system administrators at any level.
Microsoft has revolutionized the world of system management and command-line shells with its release of Windows PowerShell, and Lee Holmes gives you practical tools and inside advice that will make you a more productive user and administrator. You will be able to solve everything from automating routine tasks, working with files, event logs and other forms of structured data, to managing the users and resources of complex Windows networks. Each recipe includes a focused piece of code plus discussion of how and why it works, so that you can apply the solution to similar tasks.
You get an array of recipes covering PowerShell fundamentals, common tasks, and administrator tasks, including:
- Pipelines, variables, objects, looping and flow control, strings and unstructured text, calculations and math
- Simple files; structured files; Internet-enabled scripts; code reuse; lists, arrays and hashtables; user feedback; error management; environmental awareness; script signing; and more
- Files and directories, registry manipulation, comparing data, event logs, process cmdlets, service cmdlets, Active Directory, enterprise computer management, and more
Those who administer Microsoft's Exchange 2007 and System Center Operations Manager (formerly MOM) will also benefit from this book, with separate chapters devoted to these servers. All Windows administrators will appreciate the appendices that include a PowerShell language quick reference, and a reference to the .NET, WMI and COM objects that PowerShell scripters will use often.
With working scripts, tutorials, and references all in one volume, Windows PowerShell Cookbook will turbocharge the productivity of any Windows administrator.
This volume shows how to build scripts and utilities to automate system tasks or create powerful system management tools to handle the day-to-day tasks that drive a Windows administrator's life.
PowerShell replaces cobbled-together assemblies of third-party management tools with an elegant programming language and a powerful scripting shell for the Windows environment. In the tradition of Manning's ground breaking "In Action" series, this book comes from right from the source. Written by Bruce Payette, one of principal creators of PowerShell, Windows PowerShell in Action shows you how to build scripts and utilities to automate system tasks or create powerful system management tools to handle the day-to-day tasks that drive a Windows administrator's life. Because it's based on the .NET platform, PowerShell is also a powerful tool for developers and power users.
Windows PowerShell in Action was written by Bruce Payette, one of the founding members of the Windows PowerShell team, co-designer of the PowerShell language and the principal author of the PowerShell language implementation. The book enables you to get the most out of the PowerShell environment. Using many examples, both small and large, this book illustrates the features of the language and environment and shows how to compose those features into solutions, quickly and effectively.
This book is designed for anyone who wants to learn PowerShell and use it well. Rather than simply being a book of recipes to read and apply, this book gives you the deep knowledge about how PowerShell works and how to apply it.
This complete learning resource not only offers a task-based introduction to the Windows PowerShell scripting language and environment, it also provides hundreds of tested scripts that readers can use right away to administer Windows systems.
Do you know how to use Windows PowerShell to navigate the filesystem and manage files and folders? Or how to retrieve a web page? This introduction to the PowerShell language and scripting environment provides more than 430 task-oriented recipes to help you solve the most complex and pressing problems, and includes more than 100 tried-and-tested scripts that intermediate to advanced system administrators can copy and use immediately.
You'll find hands-on tutorials on fundamentals, common tasks, and administrative jobs that you can apply whether you're on a client or server version of Windows. You also get quick references to technologies used in conjunction with PowerShell, including format specifiers and frequently referenced registry keys to selected .NET, COM, and WMI classes. With Windows PowerShell Cookbook, youll get more done in less time.
- Take a tour of PowerShells core features, including the command model, object-based pipeline, and ubiquitous scripting
- Learn PowerShell fundamentals such as the interactive shell and fundamental pipeline and object concepts
- Perform common tasks that involve working with files, Internet-connected scripts, user interaction, and more
- Solve tasks in systems and enterprise management, such as working with Active Directory, the filesystem, registry, event logs, processes, and services
About the Author
Lee Holmes is a developer on the Microsoft Windows PowerShell team, and has been an authoritative source of information about PowerShell since its earliest betas. His vast experience with Windows PowerShell enables him to integrate both the 'how' and the 'why' into discussions. Lee's involvement with the PowerShell and administration community (via newsgroups, mailing lists, and blogs) gives him a great deal of insight into the problems faced by all levels of administrators and PowerShell users alike.
Table of Contents
Foreword; Foreword to the First Edition; Glue, Enablers, and a WSH; That Lee Guy; Preface; Who This Book Is For; How This Book Is Organized; What You Need to Use This Book; Conventions Used in This Book; Code Examples; Comments and Questions; Safari® Books Online; Acknowledgments; Tour; A Guided Tour of Windows PowerShell; Introduction; An Interactive Shell; Structured Commands (Cmdlets); Deep Integration of Objects; Administrators as First-Class Users; Composable Commands; Techniques to Protect You from Yourself; Common Discovery Commands; Ubiquitous Scripting; Ad Hoc Development; Bridging Technologies; Namespace Navigation Through Providers; Much, Much More; Fundamentals; Chapter 1: The Windows PowerShell Interactive Shell; 1.1 Introduction; 1.2 Run Programs, Scripts, and Existing Tools; 1.3 Resolve Errors Calling Native Executables; 1.4 Run a PowerShell Command; 1.5 Invoke a Long-Running or Background Command; 1.6 Notify Yourself of Job Completion; 1.7 Customize Your Shell, Profile, and Prompt; 1.8 Find a Command to Accomplish a Task; 1.9 Get Help on a Command; 1.10 Program: Search Help for Text; 1.11 Program: View PowerShell's HTML Help; 1.12 Launch PowerShell at a Specific Location; 1.13 Invoke a PowerShell Command or Script from Outside PowerShell; 1.14 Customize the Shell to Improve Your Productivity; 1.15 Program: Learn Aliases for Common Commands; 1.16 Program: Learn Aliases for Common Parameters; 1.17 Access and Manage Your Console History; 1.18 Program: Create Scripts from Session History; 1.19 Invoke a Command from Your Session History; 1.20 Program: Search Formatted Output for a Pattern; 1.21 Interactively View and Process Command Output; 1.22 Store the Output of a Command into a File; 1.23 Add Information to the End of a File; 1.24 Record a Transcript of Your Shell Session; 1.25 Extend Your Shell with Additional Commands; 1.26 Use Commands from Customized Shells; 1.27 Save State Between Sessions; Chapter 2: Pipelines; 2.1 Introduction; 2.2 Filter Items in a List or Command Output; 2.3 Group and Pivot Data by Name; 2.4 Program: Simplify Most Where-Object Filters; 2.5 Program: Interactively Filter Lists of Objects; 2.6 Work with Each Item in a List or Command Output; 2.7 Automate Data-Intensive Tasks; 2.8 Program: Simplify Most Foreach-Object Pipelines; 2.9 Intercept Stages of the Pipeline; 2.10 Automatically Capture Pipeline Output; 2.11 Capture and Redirect Binary Process Output; Chapter 3: Variables and Objects; 3.1 Introduction; 3.2 Display the Properties of an Item as a List; 3.3 Display the Properties of an Item as a Table; 3.4 Store Information in Variables; 3.5 Access Environment Variables; 3.6 Program: Retain Changes to Environment Variables Set by a Batch File; 3.7 Control Access and Scope of Variables and Other Items; 3.8 Program: Create a Dynamic Variable; 3.9 Work with .NET Objects; 3.10 Create an Instance of a .NET Object; 3.11 Program: Create Instances of Generic Objects; 3.12 Reduce Typing for Long Class Names; 3.13 Use a COM Object; 3.14 Learn About Types and Objects; 3.15 Get Detailed Documentation About Types and Objects; 3.16 Add Custom Methods and Properties to Objects; 3.17 Create and Initialize Custom Objects; 3.18 Add Custom Methods and Properties to Types; Chapter 4: Looping and Flow Control; 4.1 Introduction; 4.2 Make Decisions with Comparison and Logical Operators; 4.3 Adjust Script Flow Using Conditional Statements; 4.4 Manage Large Conditional Statements with Switches; 4.5 Repeat Operations with Loops; 4.6 Add a Pause or Delay; Chapter 5: Strings and Unstructured Text; 5.1 Introduction; 5.2 Create a String; 5.3 Create a Multiline or Formatted String; 5.4 Place Special Characters in a String; 5.5 Insert Dynamic Information in a String; 5.6 Prevent a String from Including Dynamic Information; 5.7 Place Formatted Information in a String; 5.8 Search a String for Text or a Pattern; 5.9 Replace Text in a String; 5.10 Split a String on Text or a Pattern; 5.11 Combine Strings into a Larger String; 5.12 Convert a String to Upper/Lowercase; 5.13 Trim a String; 5.14 Format a Date for Output; 5.15 Program: Convert Text Streams to Objects; 5.16 Generate Large Reports and Text Streams; 5.17 Generate Source Code and Other Repetitive Text; Chapter 6: Calculations and Math; 6.1 Introduction; 6.2 Perform Simple Arithmetic; 6.3 Perform Complex Arithmetic; 6.4 Measure Statistical Properties of a List; 6.5 Work with Numbers as Binary; 6.6 Simplify Math with Administrative Constants; 6.7 Convert Numbers Between Bases; Chapter 7: Lists, Arrays, and Hashtables; 7.1 Introduction; 7.2 Create an Array or List of Items; 7.3 Create a Jagged or Multidimensional Array; 7.4 Access Elements of an Array; 7.5 Visit Each Element of an Array; 7.6 Sort an Array or List of Items; 7.7 Determine Whether an Array Contains an Item; 7.8 Combine Two Arrays; 7.9 Find Items in an Array That Match a Value; 7.10 Compare Two Lists; 7.11 Remove Elements from an Array; 7.12 Find Items in an Array Greater or Less Than a Value; 7.13 Use the ArrayList Class for Advanced Array Tasks; 7.14 Create a Hashtable or Associative Array; 7.15 Sort a Hashtable by Key or Value; Chapter 8: Utility Tasks; 8.1 Introduction; 8.2 Get the System Date and Time; 8.3 Measure the Duration of a Command; 8.4 Read and Write from the Windows Clipboard; 8.5 Generate a Random Number or Object; 8.6 Program: Search the Windows Start Menu; 8.7 Program: Show Colorized Script Content; Common Tasks; Chapter 9: Simple Files; 9.1 Introduction; 9.2 Get the Content of a File; 9.3 Search a File for Text or a Pattern; 9.4 Parse and Manage Text-Based Logfiles; 9.5 Parse and Manage Binary Files; 9.6 Create a Temporary File; 9.7 Search and Replace Text in a File; 9.8 Program: Get the Encoding of a File; 9.9 Program: View the Hexadecimal Representation of Content; Chapter 10: Structured Files; 10.1 Introduction; 10.2 Access Information in an XML File; 10.3 Perform an XPath Query Against XML; 10.4 Convert Objects to XML; 10.5 Modify Data in an XML File; 10.6 Easily Import and Export Your Structured Data; 10.7 Store the Output of a Command in a CSV or Delimited File; 10.8 Import CSV and Delimited Data from a File; 10.9 Use Excel to Manage Command Output; 10.10 Parse and Interpret PowerShell Scripts; Chapter 11: Code Reuse; 11.1 Introduction; 11.2 Write a Script; 11.3 Write a Function; 11.4 Find a Verb Appropriate for a Command Name; 11.5 Write a Script Block; 11.6 Return Data from a Script, Function, or Script Block; 11.7 Package Common Commands in a Module; 11.8 Write Commands That Maintain State; 11.9 Selectively Export Commands from a Module; 11.10 Diagnose and Interact with Internal Module State; 11.11 Handle Cleanup Tasks When a Module Is Removed; 11.12 Access Arguments of a Script, Function, or Script Block; 11.13 Add Validation to Parameters; 11.14 Accept Script Block Parameters with Local Variables; 11.15 Dynamically Compose Command Parameters; 11.16 Provide -WhatIf, -Confirm, and Other Cmdlet Features; 11.17 Add Help to Scripts or Functions; 11.18 Add Custom Tags to a Function or Script Block; 11.19 Access Pipeline Input; 11.20 Write Pipeline-Oriented Scripts with Cmdlet Keywords; 11.21 Write a Pipeline-Oriented Function; 11.22 Organize Scripts for Improved Readability; 11.23 Invoke Dynamically Named Commands; 11.24 Program: Enhance or Extend an Existing Cmdlet; Chapter 12: Internet-Enabled Scripts; 12.1 Introduction; 12.2 Download a File from the Internet; 12.3 Download a Web Page from the Internet; 12.4 Program: Get-PageUrls; 12.5 Connect to a Web Service; 12.6 Program: Connect-WebService; 12.7 Export Command Output as a Web Page; 12.8 Send an Email; 12.9 Program: Send-MailMessage; 12.10 Program: Interact with Internet Protocols; Chapter 13: User Interaction; 13.1 Introduction; 13.2 Read a Line of User Input; 13.3 Read a Key of User Input; 13.4 Program: Display a Menu to the User; 13.5 Display Messages and Output to the User; 13.6 Provide Progress Updates on Long-Running Tasks; 13.7 Write Culture-Aware Scripts; 13.8 Support Other Languages in Script Output; 13.9 Program: Invoke a Script Block with Alternate Culture Settings; 13.10 Access Features of the Host's User Interface; 13.11 Program: Add a Graphical User Interface to Your Script; 13.12 Interact with UI Frameworks and STA Objects; Chapter 14: Debugging; 14.1 Introduction; 14.2 Prevent Common Scripting Errors; 14.3 Trace Script Execution; 14.4 Set a Script Breakpoint; 14.5 Debug a Script When It Encounters an Error; 14.6 Create a Conditional Breakpoint; 14.7 Investigate System State While Debugging; 14.8 Program: Watch an Expression for Changes; 14.9 Program: Get Script Code Coverage; Chapter 15: Tracing and Error Management; 15.1 Introduction; 15.2 Determine the Status of the Last Command; 15.3 View the Errors Generated by a Command; 15.4 Manage the Error Output of Commands; 15.5 Program: Resolve an Error; 15.6 Configure Debug, Verbose, and Progress Output; 15.7 Handle Warnings, Errors, and Terminating Errors; 15.8 Output Warnings, Errors, and Terminating Errors; 15.9 Program: Analyze a Script's Performance Profile; Chapter 16: Environmental Awareness; 16.1 Introduction; 16.2 View and Modify Environment Variables; 16.3 Access Information About Your Command's Invocation; 16.4 Program: Investigate the InvocationInfo Variable; 16.5 Find Your Script's Name; 16.6 Find Your Script's Location; 16.7 Find the Location of Common System Paths; 16.8 Get the Current Location; 16.9 Safely Build File Paths Out of Their Components; 16.10 Interact with PowerShell's Global Environment; 16.11 Determine PowerShell Version Information; Chapter 17: Extend the Reach of Windows PowerShell; 17.1 Introduction; 17.2 Automate Programs Using COM Scripting Interfaces; 17.3 Program: Query a SQL Data Source; 17.4 Access Windows Performance Counters; 17.5 Access Windows API Functions; 17.6 Program: Invoke Simple Windows API Calls; 17.7 Define or Extend a .NET Class; 17.8 Add Inline C# to Your PowerShell Script; 17.9 Access a .NET SDK Library; 17.10 Create Your Own PowerShell Cmdlet; 17.11 Add PowerShell Scripting to Your Own Program; Chapter 18: Security and Script Signing; 18.1 Introduction; 18.2 Enable Scripting Through an Execution Policy; 18.3 Disable Warnings for UNC Paths; 18.4 Sign a PowerShell Script, Module, or Formatting File; 18.5 Program: Create a Self-Signed Certificate; 18.6 Manage PowerShell Security in an Enterprise; 18.7 Block Scripts by Publisher, Path, or Hash; 18.8 Verify the Digital Signature of a PowerShell Script; 18.9 Securely Handle Sensitive Information; 18.10 Securely Request Usernames and Passwords; 18.11 Program: Start a Process as Another User; 18.12 Program: Run a Temporarily Elevated Command; 18.13 Securely Store Credentials on Disk; 18.14 Access User and Machine Certificates; 18.15 Program: Search the Certificate Store; 18.16 Add and Remove Certificates; 18.17 Manage Security Descriptors in SDDL Form; Chapter 19: Integrated Scripting Environment; 19.1 Introduction; 19.2 Debug a Script; 19.3 Customize Text and User Interface Colors; 19.4 Connect to a Remote Computer; 19.5 Extend ISE Functionality Through Its Object Model; 19.6 Add an Item to the Tools Menu; Administrator Tasks; Chapter 20: Files and Directories; 20.1 Introduction; 20.2 Determine the Current Location; 20.3 Get the Files in a Directory; 20.4 Find All Files Modified Before a Certain Date; 20.5 Clear the Content of a File; 20.6 Manage and Change the Attributes of a File; 20.7 Find Files That Match a Pattern; 20.8 Manage Files That Include Special Characters; 20.9 Program: Get Disk Usage Information; 20.10 Monitor a File for Changes; 20.11 Get the Version of a DLL or Executable; 20.12 Program: Get the MD5 or SHA1 Hash of a File; 20.13 Create a Directory; 20.14 Remove a File or Directory; 20.15 Rename a File or Directory; 20.16 Move a File or Directory; 20.17 Program: Move or Remove a Locked File; 20.18 Get the ACL of a File or Directory; 20.19 Set the ACL of a File or Directory; 20.20 Program: Add Extended File Properties to Files; 20.21 Program: Create a Filesystem Hard Link; 20.22 Program: Create a ZIP Archive; Chapter 21: The Windows Registry; 21.1 Introduction; 21.2 Navigate the Registry; 21.3 View a Registry Key; 21.4 Modify or Remove a Registry Key Value; 21.5 Create a Registry Key Value; 21.6 Remove a Registry Key; 21.7 Safely Combine Related Registry Modifications; 21.8 Add a Site to an Internet Explorer Security Zone; 21.9 Modify Internet Explorer Settings; 21.10 Program: Search the Windows Registry; 21.11 Get the ACL of a Registry Key; 21.12 Set the ACL of a Registry Key; 21.13 Work with the Registry of a Remote Computer; 21.14 Program: Get Registry Items from Remote Machines; 21.15 Program: Get Properties of Remote Registry Keys; 21.16 Program: Set Properties of Remote Registry Keys; 21.17 Discover Registry Settings for Programs; Chapter 22: Comparing Data; 22.1 Introduction; 22.2 Compare the Output of Two Commands; 22.3 Determine the Differences Between Two Files; 22.4 Verify Integrity of File Sets; Chapter 23: Event Logs; 23.1 Introduction; 23.2 List All Event Logs; 23.3 Get the Newest Entries from an Event Log; 23.4 Find Event Log Entries with Specific Text; 23.5 Retrieve and Filter Event Log Entries; 23.6 Find Event Log Entries by Their Frequency; 23.7 Back Up an Event Log; 23.8 Create or Remove an Event Log; 23.9 Write to an Event Log; 23.10 Run a PowerShell Script for Windows Event Log Entries; 23.11 Clear or Maintain an Event Log; 23.12 Access Event Logs of a Remote Machine; Chapter 24: Processes; 24.1 Introduction; 24.2 List Currently Running Processes; 24.3 Launch the Application Associated with a Document; 24.4 Launch a Process; 24.5 Stop a Process; 24.6 Debug a Process; Chapter 25: System Services; 25.1 Introduction; 25.2 List All Running Services; 25.3 Manage a Running Service; 25.4 Configure a Service; Chapter 26: Active Directory; 26.1 Introduction; 26.2 Test Active Directory Scripts on a Local Installation; 26.3 Create an Organizational Unit; 26.4 Get the Properties of an Organizational Unit; 26.5 Modify Properties of an Organizational Unit; 26.6 Delete an Organizational Unit; 26.7 Get the Children of an Active Directory Container; 26.8 Create a User Account; 26.9 Program: Import Users in Bulk to Active Directory; 26.10 Search for a User Account; 26.11 Get and List the Properties of a User Account; 26.12 Modify Properties of a User Account; 26.13 Change a User Password; 26.14 Create a Security or Distribution Group; 26.15 Search for a Security or Distribution Group; 26.16 Get the Properties of a Group; 26.17 Find the Owner of a Group; 26.18 Modify Properties of a Security or Distribution Group; 26.19 Add a User to a Security or Distribution Group; 26.20 Remove a User from a Security or Distribution Group; 26.21 List a User's Group Membership; 26.22 List the Members of a Group; 26.23 List the Users in an Organizational Unit; 26.24 Search for a Computer Account; 26.25 Get and List the Properties of a Computer Account; Chapter 27: Enterprise Computer Management; 27.1 Introduction; 27.2 Join a Computer to a Domain or Workgroup; 27.3 Remove a Computer from a Domain; 27.4 Program: List Logon or Logoff Scripts for a User; 27.5 Program: List Startup or Shutdown Scripts for a Machine; 27.6 Deploy PowerShell-Based Logon Scripts; 27.7 Enable or Disable the Windows Firewall; 27.8 Open or Close Ports in the Windows Firewall; 27.9 Program: List All Installed Software; 27.10 Uninstall an Application; 27.11 Manage Computer Restore Points; 27.12 Reboot or Shut Down a Computer; 27.13 Determine Whether a Hotfix Is Installed; 27.14 Manage Scheduled Tasks on a Computer; 27.15 Retrieve Printer Information; 27.16 Retrieve Printer Queue Statistics; 27.17 Manage Printers and Print Queues; 27.18 Program: Summarize System Information; 27.19 Renew a DHCP Lease; 27.20 Assign a Static IP Address; 27.21 List All IP Addresses for a Computer; 27.22 List Network Adapter Properties; Chapter 28: Windows Management Instrumentation; 28.1 Introduction; 28.2 Access Windows Management Instrumentation Data; 28.3 Modify the Properties of a WMI Instance; 28.4 Invoke a Method on a WMI Class; 28.5 Program: Determine Properties Available to WMI Filters; 28.6 Program: Search for WMI Classes; 28.7 Use .NET to Perform Advanced WMI Tasks; 28.8 Improve the Performance of Large-Scale WMI Operations; 28.9 Convert a VBScript WMI Script to PowerShell; Chapter 29: Remoting; 29.1 Introduction; 29.2 Find Commands That Support Their Own Remoting; 29.3 Program: Invoke a PowerShell Expression on a Remote Machine; 29.4 Test Connectivity Between Two Computers; 29.5 Limit Networking Scripts to Hosts That Respond; 29.6 Enable PowerShell Remoting on a Computer; 29.7 Enable Remote Desktop on a Computer; 29.8 Program: Remotely Enable PowerShell Remoting; 29.9 Configure User Permissions for Remoting; 29.10 Enable Remoting to Workgroup Computers; 29.11 Interactively Manage a Remote Computer; 29.12 Invoke a Command on a Remote Computer; 29.13 Implicitly Invoke Commands from a Remote Computer; 29.14 Create Sessions with Full Network Access; 29.15 Pass Variables to Remote Sessions; 29.16 Configure Advanced Remoting Options; 29.17 Invoke a Command on Many Computers; 29.18 Run a Local Script on a Remote Computer; 29.19 Program: Transfer a File to a Remote Computer; 29.20 Determine Whether a Script Is Running on a Remote Computer; 29.21 Program: Create a Task-Specific Remoting Endpoint; Chapter 30: Transactions; 30.1 Introduction; 30.2 Safely Experiment with Transactions; 30.3 Change Error Recovery Behavior in Transactions; Chapter 31: Event Handling; 31.1 Introduction; 31.2 Respond to Automatically Generated Events; 31.3 Create and Respond to Custom Events; 31.4 Create a Temporary Event Subscription; 31.5 Forward Events from a Remote Computer; 31.6 Investigate Internal Event Action State; 31.7 Use a Script Block as a .NET Delegate or Event Handler; References; PowerShell Language and Environment; Commands and Expressions; Comments; Variables; Booleans; Strings; Numbers; Arrays and Lists; Hashtables (Associative Arrays); XML; Simple Operators; Comparison Operators; Conditional Statements; Looping Statements; Working with the .NET Framework; Writing Scripts, Reusing Functionality; Managing Errors; Formatting Output; Capturing Output; Common Customization Points; Regular Expression Reference; XPath Quick Reference; .NET String Formatting; String Formatting Syntax; Standard Numeric Format Strings; Custom Numeric Format Strings; .NET DateTime Formatting; Custom DateTime Format Strings; Selected .NET Classes and Their Uses; WMI Reference; Selected COM Objects and Their Uses; Selected Events and Their Uses; Standard PowerShell Verbs; Colophon;