Windows PowerShell Cookbook

Lee Holmes

Note

You are reading the text of an O'Reilly book that's under development. The author is publishing the book to this site as it's being written, and we're putting it here to get feedback from you. This book uses the Open Feedback Publishing System (OFPS), an O'Reilly experiment that tries to bridge the gap between private manuscripts and public blogs.

NOTICE FROM PAVLECK.NET:

This copy of the Windows PowerShell Cookbook is being shared by Pavleck.NET and is allowed in accordance with the above mentioned CC license. This copy is from March 29th, 2010 - there may have been many changes made since that time, it is highly encouraged that you purchase the actual book. And it's even more highly encouraged that you purchase it from Amazon using my associate link so I can get some cash to pay for the bandwidth. If you don't want to use it, that's fine - here's a normal link. The book is scheduled for release on August 15th, 2010.

This book is ALSO AVAILABLE AS A PDF FILE

 

 

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
Acknowledgments
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
1. The Windows PowerShell Interactive Shell
Introduction
Run Programs, Scripts, and Existing Tools
Resolve Errors Calling Native Executables
Run a PowerShell Command
Invoke a Long-Running or Background Command
Notify Yourself of Job Completion
Customize Your Shell, Profile, and Prompt
Find a Command to Accomplish a Task
Get Help on a Command
Program: Search Help for Text
Program: View PowerShell's HTML Help
Launch PowerShell at a Specific Location
Invoke a PowerShell Command or Script From Outside PowerShell
Customize the Shell to Improve Your Productivity
Program: Learn Aliases for Common Commands
Program: Learn Aliases for Common Parameters
Access and Manage Your Console History
Program: Create Scripts From Session History
Invoke a Command From your Session History
Program: Search Formatted Output for a Pattern
Interactively View and Process Command Output
Store the Output of a Command into a File
Add Information to the End of a File
Record a Transcript of Your Shell Session
Extend Your Shell with Additional Commands
Use Commands from Customized Shells
Save State Between Sessions
2. Pipelines
Introduction
Filter Items in a List or Command Output
Group and Pivot Data by Name
Program: Simplify Most Where-Object Filters
Program: Interactively Filter Lists of Objects
Work with Each Item in a List or Command Output
Automate Data-Intensive Tasks
Program: Simplify Most Foreach-Object Pipelines
Intercept Stages of the Pipeline
Automatically Capture Pipeline Output
Capture and Redirect Binary Process Output
3. Variables and Objects
Introduction
Display the Properties of an Item As a List
Display the Properties of an Item As a Table
Store Information in Variables
Access Environment Variables
Program: Retain Changes to Environment Variables Set by a Batch File
Control Access and Scope of Variables and Other Items
Program: Create a Dynamic Variable
Work with .NET Objects
Create an Instance of a .NET Object
Program: Create Instances of Generic Objects
Reduce Typing for Long Class Names
Use a COM Object
Learn About Types and Objects
Get Detailed Documentation About Types and Objects
Add Custom Methods and Properties to Objects
Create and Initialize Custom Objects
Add Custom Methods and Properties to Types
4. Looping and Flow Control
Introduction
Make Decisions with Comparison and Logical Operators
Adjust Script Flow Using Conditional Statements
Manage Large Conditional Statements with Switches
Repeat Operations with Loops
Add a Pause or Delay
5. Strings and Unstructured Text
Introduction
Create a String
Create a Multiline or Formatted String
Place Special Characters in a String
Insert Dynamic Information in a String
Prevent a String from Including Dynamic Information
Place Formatted Information in a String
Search a String for Text or a Pattern
Replace Text in a String
Split a String on Text or a Pattern
Combine Strings into a Larger String
Convert a String to Upper/Lowercase
Trim a String
Format a Date for Output
Program: Convert Text Streams to Objects
Generate Large Reports and Text Streams
Generate Source Code and other Repetitive Text
6. Calculations and Math
Introduction
Perform Simple Arithmetic
Perform Complex Arithmetic
Measure Statistical Properties of a List
Work with Numbers As Binary
Simplify Math with Administrative Constants
Convert Numbers Between Bases
7. Lists, Arrays, and Hashtables
Introduction
Create an Array or List of Items
Create a Jagged or Multidimensional Array
Access Elements of an Array
Visit Each Element of an Array
Sort an Array or List of Items
Determine Whether an Array Contains an Item
Combine Two Arrays
Find Items in an Array That Match a Value
Compare Two Lists
Remove Elements from an Array
Find Items in an Array Greater or Less Than a Value
Use the ArrayList Class for Advanced Array Tasks
Create a Hashtable or Associative Array
Sort a Hashtable by Key or Value
8. Utility Tasks
Introduction
Get the System Date and Time
Measure the Duration of a Command
Read and Write from the Windows Clipboard
Generate a Random Number or Object
Program: Search the Windows Start Menu
Program: Show Colorized Script Content
9. Simple Files
Introduction
Get the Content of a File
Search a File for Text or a Pattern
Parse and Manage Text-Based Logfiles
Parse and Manage Binary Files
Create a Temporary File
Search and Replace Text in a File
Program: Get the Encoding of a File
Program: View the Hexadecimal Representation of Content
10. Structured Files
Introduction
Access Information in an XML File
Perform an XPath Query Against XML
Convert Objects to XML
Modify Data in an XML File
Easily Import and Export Your Structured Data
Store the Output of a Command in a CSV or Delimited File
Import CSV and Delimited Data from a File
Use Excel to Manage Command Output
Parse and Interpret PowerShell Scripts
11. Code Reuse
Introduction
Write a Script
Write a Function
Find a Verb Appropriate for a Command Name
Write a Script Block
Return Data from a Script, Function, or Script Block
Package Common Commands in a Module
Write Commands that Maintain State
Selectively Export Commands from a Module
Diagnose and Interact with Internal Module State
Handle Cleanup Tasks when a Module is Removed
Access Arguments of a Script, Function, or Script Block
Add Validation to Parameters
Accept Script Block Parameters with Local Variables
Dynamically Compose Command Parameters
Provide -WhatIf, -Confirm, and Other Cmdlet Features
Add Help to Scripts or Functions
Add Custom Tags to a Function, or Script Block
Access Pipeline Input
Write Pipeline-Oriented Scripts with Cmdlet Keywords
Write a Pipeline-Oriented Function
Organize Scripts for Improved Readability
Invoke Dynamically-Named Commands
Program: Enhance or Extend an Existing Cmdlet
12. Internet-Enabled Scripts
Introduction
Download a File from the Internet
Download a Web Page from the Internet
Program: Get-PageUrls
Connect to a Webservice
Program: Connect-WebService
Export Command Output As a Web Page
Send an Email
Program: Send-MailMessage
Program: Interact with Internet Protocols
13. User Interaction
Introduction
Read a Line of User Input
Read a Key of User Input
Program: Display a Menu to the User
Display Messages and Output to the User
Provide Progress Updates on Long-Running Tasks
Write Culture-Aware Scripts
Support Other Languages in Script Output
Program: Invoke a Script Block with Alternate Culture Settings
Access Features of the Host's User Interface
Program: Add a Graphical User Interface to Your Script
Interact With UI Frameworks and STA Objects
14. Debugging
Introduction
Prevent Common Scripting Errors
Trace Script Execution
Set a Script Breakpoint
Debug a Script when it Encounters an Error
Create a Conditional Breakpoint
Investigate System State While Debugging
Program: Watch an Expression for Changes
Program: Get Script Code Coverage
15. Tracing and Error Management
Introduction
Determine the Status of the Last Command
View the Errors Generated by a Command
Manage the Error Output of Commands
Program: Resolve an Error
Configure Debug, Verbose, and Progress Output
Handle Warnings, Errors, and Terminating Errors
Output Warnings, Errors, and Terminating Errors
Program: Analyze a Script's Performance Profile
16. Environmental Awareness
Introduction
View and Modify Environment Variables
Access Information About Your Command's Invocation
Program: Investigate the InvocationInfo Variable
Find Your Script's Name
Find Your Script's Location
Find the Location of Common System Paths
Get the Current Location
Safely Build File Paths Out of Their Components
Interact with PowerShell's Global Environment
Determine PowerShell Version Information
17. Extend the Reach of Windows PowerShell
Introduction
Automate Programs Using COM Scripting Interfaces
Program: Query a SQL Data Source
Access Windows Performance Counters
Access Windows API Functions
Program: Invoke Simple Windows API Calls
Define or Extend a .NET Class
Add Inline C# to your PowerShell Script
Access a .NET SDK Library
Create Your Own PowerShell Cmdlet
Add PowerShell Scripting to Your Own Program
18. Security and Script Signing
Introduction
Enable Scripting Through an Execution Policy
Disable Warnings for UNC Paths
Sign a PowerShell Script, Module, or Formatting File
Program: Create a Self-Signed Certificate
Manage PowerShell Security in an Enterprise
Block Scripts by Publisher, Path, or Hash
Verify the Digital Signature of a PowerShell Script
Securely Handle Sensitive Information
Securely Request Usernames and Passwords
Program: Start a Process As Another User
Program: Run a Temporarily Elevated Command
Securely Store Credentials on Disk
Access User and Machine Certificates
Program: Search the Certificate Store
Add and Remove Certificates
Manage Security Descriptors in SDDL Form
19. Integrated Scripting Environment
Introduction
Debug a Script
Customize Text and User Interface Colors
Connect to a Remote Computer
Extend ISE Functionality Through its Object Model
Add an Item to the Tools Menu
20. Files and Directories
Introduction
Determine the Current Location
Get the Files in a Directory
Find All Files Modified Before a Certain Date
Clear the Content of a File
Manage and Change the Attributes of a File
Find Files That Match a Pattern
Manage Files That Include Special Characters
Program: Get Disk Usage Information
Monitor a File for Changes
Get the Version of a DLL or Executable
Program: Get the MD5 or SHA1 Hash of a File
Create a Directory
Remove a File or Directory
Rename a File or Directory
Move a File or Directory
Program: Move or Remove a Locked File
Get the ACL of a File or Directory
Set the ACL of a File or Directory
Program: Add Extended File Properties to Files
Program: Create a Filesystem Hard Link
Program: Create a ZIP Archive
21. The Windows Registry
Introduction
Navigate the Registry
View a Registry Key
Modify or Remove a Registry Key Value
Create a Registry Key Value
Remove a Registry Key
Safely Combine Related Registry Modifications
Add a Site to an Internet Explorer Security Zone
Modify Internet Explorer Settings
Program: Search the Windows Registry
Get the ACL of a Registry Key
Set the ACL of a Registry Key
Work with the Registry of a Remote Computer
Program: Get Registry Items from Remote Machines
Program: Get Properties of Remote Registry Keys
Program: Set Properties of Remote Registry Keys
Discover Registry Settings for Programs
22. Comparing Data
Introduction
Compare the Output of Two Commands
Determine the Differences Between Two Files
Verify Integrity of File Sets
23. Event Logs
Introduction
List All Event Logs
Get the Newest Entries from an Event Log
Find Event Log Entries with Specific Text
Retrieve and Filter Event Log Entries
Find Event Log Entries by Their Frequency
Back Up an Event Log
Create or Remove an Event Log
Write to an Event Log
Run a PowerShell Script for Windows Event Log Entries
Clear or Maintain an Event Log
Access Event Logs of a Remote Machine
24. Processes
Introduction
List Currently Running Processes
Launch the Application Associated with a Document
Launch a Process
Stop a Process
Debug a Process
25. System Services
Introduction
List All Running Services
Manage a Running Service
Configure a Service
26. Active Directory
Introduction
Test Active Directory Scripts on a Local Installation
Create an Organizational Unit
Get the Properties of an Organizational Unit
Modify Properties of an Organizational Unit
Delete an Organizational Unit
Get the Children of an Active Directory Container
Create a User Account
Program: Import Users in Bulk to Active Directory
Search for a User Account
Get and List the Properties of a User Account
Modify Properties of a User Account
Change a User Password
Create a Security or Distribution Group
Search for a Security or Distribution Group
Get the Properties of a Group
Find the Owner of a Group
Modify Properties of a Security or Distribution Group
Add a User to a Security or Distribution Group
Remove a User from a Security or Distribution Group
List a User's Group Membership
List the Members of a Group
List the Users in an Organizational Unit
Search for a Computer Account
Get and List the Properties of a Computer Account
27. Enterprise Computer Management
Introduction
Join a Computer to a Domain or Workgroup
Remove a Computer from a Domain
Program: List Logon or Logoff Scripts for a User
Program: List Startup or Shutdown Scripts for a Machine
Deploy PowerShell-Based Logon Scripts
Enable or Disable the Windows Firewall
Open or Close Ports in the Windows Firewall
Program: List All Installed Software
Uninstall an Application
Manage Computer Restore Points
Reboot or Shut Down a Computer
Determine Whether a Hotfix Is Installed
Manage Scheduled Tasks on a Computer
Retrieve Printer Information
Retrieve Printer Queue Statistics
Manage Printers and Print Queues
Program: Summarize System Information
Renew a DHCP Lease
Assign a Static IP Address
List All IP Addresses for a Computer
List Network Adapter Properties
28. Windows Management Instrumentation
Introduction
Access Windows Management Instrumentation Data
Modify the Properties of a WMI Instance
Invoke a Method on a WMI Class
Program: Determine Properties Available to WMI Filters
Program: Search for WMI Classes
Use .NET to Perform Advanced WMI Tasks
Improve the Performance of Large-Scale WMI Operations
Convert a VBScript WMI Script to PowerShell
29. Remoting
Introduction
Find Commands That Support Their Own Remoting
Program: Invoke a PowerShell Expression on a Remote Machine
Test Connectivity Between Two Computers
Limit Networking Scripts to Hosts that Respond
Enable PowerShell Remoting on a Computer
Enable Remote Desktop on a Computer
Program: Remotely Enable PowerShell Remoting
Configure User Permissions for Remoting
Enable Remoting to Workgroup Computers
Interactively Manage a Remote Computer
Invoke a Command on a Remote Computer
Implicitly Invoke Commands From a Remote Computer
Create Sessions with Full Network Access
Pass Variables to Remote Sessions
Configure Advanced Remoting Options
Invoke a Command on Many Computers
Run a Local Script on a Remote Computer
Program: Transfer a File to a Remote Computer
Determine if a Script is Running on a Remote Computer
Program: Create a Task-Specific Remoting Endpoint
30. Transactions
Introduction
Safely Experiment With Transactions
Change Error Recovery Behavior in Transactions
31. Event Handling
Introduction
Respond to Automatically-Generated Events
Create and Respond to Custom Events
Create a Temporary Event Subscription
Forward Events from a Remote Computer
Investigate Internal Event Action State
Use a Script Block as a .NET Delegate or Event Handler
A. 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
B. Regular Expression Reference
C. XPath Quick Reference
D. .NET String Formatting
String Formatting Syntax
Standard Numeric Format Strings
Custom Numeric Format Strings
E. .NET DateTime Formatting
Custom DateTime Format Strings
F. Selected .NET Classes and Their Uses
G. WMI Reference
H. Selected COM Objects and Their Uses
I. Selected Events and Their Uses
J. Standard PowerShell Verbs