Windows PowerShell in Action

Book description

Second edition of this book is available

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. From him you will gain a deep understanding of the language and how best to use it, and you'll love his insights into why PowerShell works the way it does.



About the Technology

Windows has an easy-to-use interface, but if you want to automate it, life can get hard. That is, unless you use PowerShell, an elegant new dynamic language from Microsoft designed as an all-purpose Windows scripting tool. PowerShell lets you script administrative tasks and control Windows from the command line. Because it was specifically developed for Windows, programmers and power-users can now do things in a shell that previously required VB, VBScript, or C#.



About the Book

This book is a tutorial for sysadmins and developers introducing the PowerShell language and its environment. It 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. It's rich in interesting examples that will spark your imagination. The book covers batch scripting and string processing, COM, WMI, and even .NET and WinForms programming.



What's Inside
  • Master the PowerShell language
  • Secure scripting with PowerShell
  • How to process strings, files, and XML
  • Techniques for network and GUI programming
  • Script Windows applications like Excel
  • Author feedback at manning.com/payette


About the Reader


About the Author

Bruce Payette is a founding member of the PowerShell team at Microsoft. He is a co-designer of the PowerShell language and the principal author of the language implementation. Prior to joining Microsoft, he worked at Softway Systems and MKS, building UNIX tools for Windows.



Quotes
THE book on PowerShell, it has ALL the secrets.
- FROM THE FOREWORD by James Truher, Microsoft Corporation

Bruce is a walking encyclopedia of every good, bad, solid, and wacky language idea that has been tried... This is a book that only Bruce could have written.
- FROM THE FOREWORD by Jeffrey Snover, Windows PowerShell Architect

If all it had going for it was the authoratative pedigree of the writer, it might be worth it, but it's also well-written, well-organized, and thorough, which I think makes it invaluable as both a learning tool and a reference.
- Jeff Copeland, Slashdot.org

[It gives you] inside information, excellent examples, and a colorful writing style.
- Marc van Orsouw (MOW), www.thepowershellguy.com

The nuances of PowerShell from the lead language designer himself! Excellent content and easy readability!
- Keith Hill, Software Architect

I love this book!
- Scott Hanselman, ComputerZen.com

There's no better way to learn PowerShell than from someone on the core PowerShell team - and that's exactly what you get with this book.
- Joe Topjian, adminspotting.net

Publisher resources

View/Submit Errata

Table of contents

  1. Copyright
    1. Dedication
  2. Foreword
  3. Preface
  4. Acknowledgments
  5. About this Book
    1. Who should read this book?
    2. Roadmap
    3. Code conventions
    4. Author Online
    5. About the author
    6. About the title
    7. About the cover illustration
  6. 1. Learning PowerShell
    1. 1. Welcome to PowerShell
      1. 1.1. What is PowerShell?
        1. 1.1.1. Shells, command-lines, and scripting languages
        2. 1.1.2. Why a new shell? Why now?
        3. 1.1.3. The last mile problem
      2. 1.2. Soul of a new language
        1. 1.2.1. Learning from history
        2. 1.2.2. Leveraging .NET
      3. 1.3. Brushing up on objects
        1. 1.3.1. Reviewing object-oriented programming
        2. 1.3.2. Objects in PowerShell
      4. 1.4. Dude! Where’s my code?
        1. 1.4.1. Installing and starting PowerShell
        2. 1.4.2. Command editing
        3. 1.4.3. Command completion
        4. 1.4.4. Evaluating basic expressions
        5. 1.4.5. Processing data
          1. Sorting objects
          2. Selecting properties from an object
          3. Processing with the Foreach-Object cmdlet
          4. Processing other kinds of data
          5. Flow control statement
      5. 1.5. Summary
    2. 2. The basics
      1. 2.1. Command concepts and terminology
        1. 2.1.1. Commands and cmdlets
        2. 2.1.2. Command categories
        3. 2.1.3. Aliases and elastic syntax
      2. 2.2. Parsing and PowerShell
        1. 2.2.1. How PowerShell parses
        2. 2.2.2. Quoting
        3. 2.2.3. Expression mode and command mode parsing
        4. 2.2.4. Statement termination
      3. 2.3. Pipelines and commands
        1. 2.3.1. Pipelines and streaming behavior
        2. 2.3.2. Parameters and parameter binding
      4. 2.4. Formatting and output
        1. 2.4.1. The formatting cmdlets
        2. 2.4.2. The outputter cmdlets
      5. 2.5. Summary
    3. 3. Working with types
      1. 3.1. Type management in the wild, wild west
        1. 3.1.1. PowerShell: a type-promiscuous language
        2. 3.1.2. The type system and type adaptation
      2. 3.2. Basic types and literals
        1. 3.2.1. Strings
          1. String representation in PowerShell
          2. Single and double-quoted strings
          3. Subexpression expansion in strings
          4. Using complex subexpressions in strings
          5. String expansion considerations
          6. Here-string literals
        2. 3.2.2. Numbers and numeric literals
          1. Specifying numeric literals
          2. The multiplier suffixes
          3. Hexadecimal literals
        3. 3.2.3. Collections: dictionaries and hashtables
          1. Creating and inspecting hashtables
          2. Modifying and manipulating hashtables
          3. Hashtables as reference types
        4. 3.2.4. Collections: arrays and sequences
          1. Collecting pipeline output as an array
          2. Array indexing
          3. Polymorphism in arrays
          4. Arrays as reference types
          5. Singleton arrays and empty arrays
        5. 3.2.5. Type literals
          1. Type name aliases
          2. Accessing static members with type literals
          3. Example: using advanced math functions
      3. 3.3. Type conversions
        1. 3.3.1. How type conversion works
        2. 3.3.2. PowerShell’s type-conversion algorithm
        3. 3.3.3. Special type conversions in parameter binding
      4. 3.4. Summary
    4. 4. Operators and expressions
      1. 4.1. Arithmetic operators
        1. 4.1.1. The addition operator
        2. 4.1.2. The multiplication operator
        3. 4.1.3. Subtraction, division, and the modulus operator
      2. 4.2. The assignment operators
        1. 4.2.1. Multiple assignments
        2. 4.2.2. Multiple assignments with type qualifiers
        3. 4.2.3. Assignment operations as value expressions
      3. 4.3. Comparison operators
        1. 4.3.1. Scalar comparisons
          1. Basic comparison rules
          2. Type conversions and comparisons
          3. Comparisons and case-sensitivity
        2. 4.3.2. Using comparison operators with collections
          1. Basic comparison operations involving collections
          2. The containment operators
      4. 4.4. The pattern matching operators
        1. 4.4.1. Wildcard patterns
        2. 4.4.2. Regular expressions
          1. Using the $matches variable
          2. Matching using named captures
          3. Parsing command output using regular expressions
      5. 4.5. Logical and bitwise operators
      6. 4.6. Summary
    5. 5. Advanced operators and variables
      1. 5.1. Operators for working with types
      2. 5.2. The unary operators
      3. 5.3. Grouping, subexpressions, and array subexpressions
      4. 5.4. Array operators
        1. 5.4.1. The comma operator “,”
        2. 5.4.2. The range operator
        3. 5.4.3. Array indexing
          1. Array slices
          2. Using the range operator with arrays
          3. Working with multi-dimensional arrays
      5. 5.5. Property and method operators
        1. 5.5.1. The “.” operator
        2. 5.5.2. Static methods and the “::” operator
      6. 5.6. The PowerShell format operator -F
      7. 5.7. Redirection and the redirection operators
      8. 5.8. Variables
      9. 5.9. Summary
    6. 6. Flow control in scripts
      1. 6.1. Using the if/elseif/else statement
      2. 6.2. The while loop
      3. 6.3. The do/while loop
      4. 6.4. The for loop
      5. 6.5. The foreach loop
      6. 6.6. Labels, break, and continue
      7. 6.7. The PowerShell switch statement
        1. 6.7.1. Basic use of the PowerShell switch statement
        2. 6.7.2. Using wildcard patterns with the switch statement
        3. 6.7.3. Using regular expressions with the switch statement
        4. 6.7.4. Processing files with the switch statement
        5. 6.7.5. Using the $switch loop enumerator in the switch statement
      8. 6.8. Flow control using cmdlets
        1. 6.8.1. The Foreach-Object cmdlet
        2. 6.8.2. The Where-Object cmdlet
      9. 6.9. The value of statements
      10. 6.10. Summary
    7. 7. Functions and scripts
      1. 7.1. Function basics
      2. 7.2. Formal parameters and the param statement
        1. 7.2.1. Specifying parameter types
        2. 7.2.2. Handling variable numbers of arguments
        3. 7.2.3. Initializing function parameters
        4. 7.2.4. Using switch parameters to define flags
        5. 7.2.5. Variables and scoping rules
        6. 7.2.6. Using variable scope modifiers
      3. 7.3. Returning values from functions
        1. 7.3.1. Debugging function output
        2. 7.3.2. The return statement
      4. 7.4. Using functions in a pipeline
        1. 7.4.1. Filters and functions
        2. 7.4.2. Functions as cmdlets
      5. 7.5. Managing functions
      6. 7.6. Scripts at long last
        1. 7.6.1. Passing arguments to scripts
        2. 7.6.2. The param statement
        3. 7.6.3. Scopes and scripts
        4. 7.6.4. Exiting scripts and the exit statement
        5. 7.6.5. Dotting scripts and functions
      7. 7.7. Summary
    8. 8. Scriptblocks and objects
      1. 8.1. Scriptblock basics
        1. 8.1.1. Invoking commands
        2. 8.1.2. Getting CommandInfo objects
        3. 8.1.3. The ScriptBlock literal
        4. 8.1.4. Defining functions at runtime
      2. 8.2. Building and manipulating objects
        1. 8.2.1. Looking at members
        2. 8.2.2. Synthetic members
        3. 8.2.3. Using Add-Member to extend objects
          1. Adding AliasProperty members
          2. Adding NoteProperty members
          3. Adding ScriptMethod members
          4. Adding ScriptProperties members
        4. 8.2.4. Using the select-object cmdlet
      3. 8.3. A closer look at the type-system plumbing
        1. 8.3.1. Adding a property
        2. 8.3.2. Shadowing an existing property
      4. 8.4. Extending the PowerShell language
        1. 8.4.1. Little languages
        2. 8.4.2. Adding a CustomClass keyword to PowerShell
      5. 8.5. Type extension
      6. 8.6. Building code at runtime
        1. 8.6.1. The Invoke-Expression cmdlet
        2. 8.6.2. The ExecutionContext variable
          1. The ExpandString() method
          2. The InvokeScript() method
          3. The NewScriptBlock() method
        3. 8.6.3. Creating functions using the function: drive
      7. 8.7. Summary
    9. 9. Errors, exceptions, and script debugging
      1. 9.1. Error handling
        1. 9.1.1. ErrorRecords and the error stream
        2. 9.1.2. The $error variable and –ErrorVariable parameter
        3. 9.1.3. The $? and $LASTEXITCODE variables
        4. 9.1.4. $ErrorActionPreference and the -ErrorAction parameter
      2. 9.2. Dealing with errors that terminate execution
        1. 9.2.1. The trap statement
        2. 9.2.2. The throw statement
      3. 9.3. Script debugging
        1. 9.3.1. Debugging with the host APIs
        2. 9.3.2. The Set-PSDebug cmdlet
        3. 9.3.3. Tracing statement execution
        4. 9.3.4. Stepping through statement execution
        5. 9.3.5. Catching undefined variables with strict mode
      4. 9.4. Nested prompts and breakpoints
        1. 9.4.1. Suspending a script while in step-mode
        2. 9.4.2. Creating a breakpoint command
        3. 9.4.3. The script call stack, or “How did I get here?”
      5. 9.5. Low-level tracing
        1. 9.5.1. The Trace-Command cmdlet
        2. 9.5.2. Tracing type conversions
        3. 9.5.3. Tracing parameter binding
      6. 9.6. The PowerShell event log
        1. 9.6.1. Examining the event log
        2. 9.6.2. Exchange 2007 and the PowerShell event log
      7. 9.7. Summary
  7. 2. Using PowerShell
    1. 10. Processing text, files, and XML
      1. 10.1. Processing unstructured text
        1. 10.1.1. Using System.String to work with text
          1. Using SplitStringOptions
          2. Analyzing word use in a document
          3. Using hashtables to count unique words
        2. 10.1.2. Using regular expressions to manipulate text
          1. Splitting strings with regular expressions
          2. Tokenizing text with regular expressions
      2. 10.2. File processing
        1. 10.2.1. Working with PSDrives
        2. 10.2.2. Working with paths that contain wildcards
          1. Suppressing wildcard processing in paths
          2. The –LiteralPath parameter
        3. 10.2.3. Reading and writing files
          1. Reading files with the Get-Content cmdlet
          2. Example: The Get-HexDump function
          3. Example: The Get-MagicNumber function
          4. Writing files
          5. All together now—Reading and writing
        4. 10.2.4. Searching files with the Select-String cmdlet
      3. 10.3. XML processing
        1. 10.3.1. Using XML as objects
          1. Adding elements to an XML object
        2. 10.3.2. Loading and saving XML files
          1. Example: The dump-doc function
          2. Example: The Select-Help function
        3. 10.3.3. Processing XML documents in a pipeline
        4. 10.3.4. Using XPath
          1. Setting up the test document
          2. The Get-XPathNavigator helper function
          3. Extracting multiple elements
          4. Performing calculations on elements
        5. 10.3.5. The Import-Clixml and Export-Clixml cmdlets
      4. 10.4. Summary
    2. 11. Getting fancy—.NET and WinForms
      1. 11.1. Using .NET from PowerShell
        1. 11.1.1. .NET basics
        2. 11.1.2. Working with assemblies
          1. Loading and exploring assemblies
        3. 11.1.3. Finding types
        4. 11.1.4. Creating instances of types
        5. 11.1.5. PowerShell is not C#—A cautionary tale
          1. Automatic unraveling of enumerators
          2. Using methods that take path names
        6. 11.1.6. Working with generic types
          1. Creating an instance of a generic type
          2. Instantiating a generic dictionary
      2. 11.2. PowerShell and the Internet
        1. 11.2.1. Example: Retrieving a web page
        2. 11.2.2. Example: Processing an RSS feed
        3. 11.2.3. Example: Writing a web server in PowerShell
          1. Reviewing how a web server works
          2. The web server script
      3. 11.3. PowerShell and graphical user interfaces
        1. 11.3.1. WinForms basics
        2. 11.3.2. Example: “My first form”
        3. 11.3.3. Example: Simple dialog
        4. 11.3.4. Example: A WinForms library
        5. 11.3.5. Example: A simple calculator
        6. 11.3.6. Example: Displaying data
        7. 11.3.7. Example: Using the GDI+ to do graphics
      4. 11.4. Summary
    3. 12. Windows objects: COM and WMI
      1. 12.1. Working with COM in PowerShell
        1. 12.1.1. Automating Windows with COM
          1. Example: “Exploring” with the Shell.Application class
          2. Example: Opening control panel items
          3. Example: Working with the WScript.Shell class
          4. Example: Sending keystrokes to a Windows application
        2. 12.1.2. Networking, applications, and toys
          1. Example: Looking up a word using Internet Explorer
          2. Example: Using the WinHTTP class to retrieve an RSS feed
          3. Example: Using Microsoft Word to do spell-checking
          4. Example: Telling stories with Windows agents
        3. 12.1.3. Using the ScriptControl object
          1. Example: Embedding VBScript code in a PowerShell script
          2. Example: Embedding JScript code in a PowerShell script
          3. Example: JScript, VBScript, and PowerShell in one script
        4. 12.1.4. Issues with COM
          1. Thread model problems
          2. Interop assemblies, wrappers, and typelibs
          3. Using the PowerShell type system to wrap COM objects
      2. 12.2. Working with WMI in PowerShell
        1. 12.2.1. Exploring WMI—what is it, and why do you care?
        2. 12.2.2. The Get-WmiObject cmdlet
        3. 12.2.3. The WMI object adapter
        4. 12.2.4. WMI shootout—VBScript versus PowerShell
          1. A VBScript example
          2. The PowerShell version
        5. 12.2.5. The WMI type shortcuts
        6. 12.2.6. Working with WMI methods
        7. 12.2.7. Working with WMI events
        8. 12.2.8. Putting modified WMI objects back
      3. 12.3. So which object model should I choose?
      4. 12.4. Summary
    4. 13. Security, security, security
      1. 13.1. Introduction to security
        1. 13.1.1. What security is
        2. 13.1.2. What security is not
        3. 13.1.3. Perception and security
          1. The Danom virus
          2. The MSH/Cibyz worm
      2. 13.2. Security modeling
        1. 13.2.1. Introduction to threat modeling
        2. 13.2.2. Classifying threats using the STRIDE model
        3. 13.2.3. Security basics: Threats, assets, and mitigations
          1. Avoid lawn gnome mitigation
          2. Blacklisting/whitelisting
          3. Authentication authorization and roles
          4. Input validation
          5. Code injection
      3. 13.3. Securing the PowerShell environment
        1. 13.3.1. Secure by default
          1. The default file association for PowerShell is Notepad
          2. No remote access to PowerShell
          3. No execution of scripts by default
        2. 13.3.2. Managing the command path
        3. 13.3.3. Choosing a script execution policy
          1. Finding the current script execution policy
          2. Changing the execution policy
      4. 13.4. Signing scripts
        1. 13.4.1. How public key encryption and one-way hashing work
        2. 13.4.2. Signing authorities and certificates
          1. Self-signed certificates
        3. 13.4.3. Creating a self-signed certificate
          1. Creating a local certificate authority
          2. Creating the signing certificate
        4. 13.4.4. Using a certificate to sign a script
          1. Setting up a test script
          2. Signing the test script
          3. Testing the integrity of the script
        5. 13.4.5. Enabling strong private key protection for your certificate
          1. Exporting the certificate
          2. Using the pfx file to sign a file
      5. 13.5. Writing secure scripts
        1. 13.5.1. Using the SecureString class
          1. Creating a SecureString object
          2. The SecureString cmdlets
        2. 13.5.2. Working with credentials
        3. 13.5.3. Avoiding Invoke-Expression
          1. The original wheres script
          2. A safer, faster wheres script
      6. 13.6. Summary
  8. A. Comparing PowerShell to other languages
    1. A.1. PowerShell and CMD.EXE
      1. A.1.1. Basic navigation and file operations
      2. A.1.2. Variables and substitution
      3. A.1.3. Running commands
      4. A.1.4. Differences in syntax
      5. A.1.5. Searching text: findstr and Select-String
      6. A.1.6. For loop equivalents
      7. A.1.7. Batch files and subroutines
      8. A.1.8. Setting the prompt
      9. A.1.9. Using doskey in PowerShell
      10. A.1.10. Using cmd.exe from PowerShell
    2. A.2. PowerShell and UNIX shells
      1. A.2.1. Example: Stopping all processes
      2. A.2.2. Example: Stopping a filtered list of processes
      3. A.2.3. Example: Calculating the size of a directory
      4. A.2.4. Example: Working with dynamic values
      5. A.2.5. Example: Monitoring the life of a process
      6. A.2.6. Example: Checking for prerelease binaries
      7. A.2.7. Example: Uppercasing a string
      8. A.2.8. Example: Inserting text into a string
    3. A.3. PowerShell and Perl
    4. A.4. PowerShell and C#
      1. A.4.1. Calling functions and commands
      2. A.4.2. Calling methods
      3. A.4.3. Returning values
      4. A.4.4. Variables and scoping
    5. A.5. PowerShell and VBScript
  9. B. Admin examples
    1. B.1. Getting active directory domain information
    2. B.2. Listing installed software features
    3. B.3. Retrieving terminal server properties
    4. B.4. List hot fixes installed on a machine
    5. B.5. Finding machines missing a hot fix
    6. B.6. Working with the event log
      1. B.6.1. Getting a specific EventLog object
      2. B.6.2. The event log as a live object
      3. B.6.3. Getting remote event logs
      4. B.6.4. Saving event logs
      5. B.6.5. Writing events
    7. B.7. Working with existing utility commands
    8. B.8. Working with Active Directory and ADSI
      1. B.8.1. Accessing the Active Directory service
      2. B.8.2. Adding a user
      3. B.8.3. Adding a group of users
      4. B.8.4. Updating user properties
      5. B.8.5. Removing users
    9. B.9. Joining two sets of data
  10. C. The PowerShell grammar
    1. C.1. Statement list
    2. C.2. Statement
      1. C.2.1. Pipeline
      2. C.2.2. The if statement
      3. C.2.3. The switch statement
      4. C.2.4. The foreach statement
      5. C.2.5. The for and while statements
      6. C.2.6. The do/while and do/until statements
      7. C.2.7. The trap statement
      8. C.2.8. The finally statement
      9. C.2.9. Flow control statements
      10. C.2.10. Function declarations
      11. C.2.11. Parameter declarations
    3. C.3. Expression
    4. C.4. Value
    5. C.5. Tokenizer rules

Product information

  • Title: Windows PowerShell in Action
  • Author(s): Bruce Payette
  • Release date: February 2007
  • Publisher(s): Manning Publications
  • ISBN: 9781932394900