The PowerShell Scripting and Toolmaking Book
The PowerShell Scripting and Toolmaking Book
About the Book
If you are looking for materials related to Microsoft Course 55039, be advised that Don no longer owns or maintains the course. Please contact the current course owner via Courseware Marketplace.
Change the Way You Code in PowerShell!
Veteran PowerShell experts and authors Don Jones and Jeffery Hicks bring you an all-new, "Agile-published" book on PowerShell Scripting and "Toolmaking." Written in their inimitable, approachable style with plenty of examples, this book focuses on an all-new narrative based on their teaching experiences since 2010. You'll not only learn "how to script" in PowerShell, you'll learn the far more important patterns and practices that will enable you to create reusable tools that look and work like native PowerShell commands. You'll also learn a world of related topics, including how to add database access to your tools, how to publish to public and private repositories, and even an introduction to key topics like Pester testing.
Thousands of IT professionals have, after experiencing Don & Jeff's classes and books, remarked that, "now I need to go home and rewrite everything I've done!" That's what this book will do for you: change the way you think about coding in PowerShell. You'll find yourself producing more efficient, more reusable tools, more easily and more quickly. You'll cement a deep understanding of not only how PowerShell works, but why it works that way, helping you make better script design decisions, and helping you execute better PowerShell tools from now on.
This book is very much "Part 3" in Don and Jeff's approach to teaching PowerShell. Part 1 is their bestselling Learn Windows PowerShell in a Month of Lunches (Manning), the "pre-scripting" PowerShell book that covers the shell's inner workings, core patterns, and basic usage. Part 2 is PowerShell Scripting in a Month of Lunches, which covers the entry-level aspects of scripting, including the foundational narrative of "the right way" to build functions and tools. This book picks up where they leave off, providing a rapid rundown of that "right way," and quickly moving into more "grown-up" scripting techniques, advanced approaches, data handling, and a lot more. As an Agile-published book, Don and Jeff can continue to update this book, as the more-advanced topics (more so than the entry-level ones) are the ones affected by new version releases.
APPLIES TO MANY VERSIONS OF POWERSHELL! If you're using PowerShell v4, v5, v5.1, or PowerShell 7, you'll find everything in this book is applicable to you in some form or another (although in PowerShell Core or PowerShell 7, any Windows-specific examples may not be functional).
NOW COVERS PESTER! Take your scripting to the next level by incorporating professional unit-testing using the ubiquitous Pester testing framework for PowerShell. A whole new section of this book covers everything you'll need to know to get started.
See the Contents
Use the "Table of Contents" link to see the complete table of contents for the full book. This does change and evolve as we work on the book. Note that the free sample reviews the complete ToC, but isn't necessarily up to date or entirely complete.
Hands-On Labs
You'll even find review questions and hands-on labs, complete with sample solutions, along with a short lab setup guide. These features will help you practice what you're learning, and make the book suitable for use in classroom settings (we recommend contacting the authors for an inexpensive site license, if you're a training center; we also provide slide decks, delivery guides, and other materials as part of a training center or trainer license).
We Publish as We Go
This is an Agile-published book, which means the authors are releasing it as they write it, and will continue to update the book as the underlying technology evolves over time. Assuming you meet the pre-requisites, this is the last book you'll ever need to buy on this topic, because your one-time purchase grants you lifetime access to updates and new content. We'll even email you via LeanPub (if you opt-in) when there's fresh content for you.
About Our Pricing
The price for this book might seem high. But that's because it's the last you'll ever have to buy. We won't be after you for a "second edition" in a couple of years, because you'll get each new update and release for free. So the higher price? This reflects that fact that you're paying up-front for what amounts to a lifetime subscription - we'll never come after you for more money for some future edition, reprinting, or update.
Check Out the Free Sample
The free sample includes sample chapters, but why bother? LeanPub has a no-questions-asked refund policy, so it's completely risk-free to grab the "real" book and see what you think. We trust you to do the right thing!
What Formats are Available?
All LeanPub books are offered in PDF, MOBI, and EPUB, and you get all three with your purchase. Note that the PDF is probably the "highest fidelity" version, especially in terms of code listings.
How Can I Contact the Authors?
We love feedback. Use the "Email the Authors" link, just below, to contact us. For feedback on the book, please provide a chapter, heading, and short snippet of text to let us know where you're looking - page numbers don't do any good, as they don't correspond with our source files.
A Note on Other Booksellers
Note that "Numbered Editions" of this book may also be available on Amazon or through other booksellers (e.g., "First Edition," "Second Edition," etc.) These are "snapshots" of the LeanPub version from a particular project milestone. Purchases made elsewhere are a one-time purchase, and do not include ongoing updates to the content. If you purchased the book elsewhere, we regrettably cannot somehow give you access to the LeanPub version, nor will you receive future updates at no charge.
Table of Contents
- About This Book
- Dedication
- Acknowledgements
-
About the Authors
- Additional Credits
- Foreword
- Feedback
-
Introduction
- Pre-Requisites
- Versioning
- The Journey
- Following Along
- Providing Feedback
- A Note on Code Listings
-
Lab Setup
- Create a Virtualized Environment
- Use the Windows 10 Sandbox
- Adding Lab Files and Configuring PowerShell
- Assumptions Going Forward
- Part 1: Review PowerShell Toolmaking
-
Functions, the Right Way
- Tool Design
- Start with a Command
- Build a Basic Function and Module
- Adding CmdletBinding and Parameterizing
- Emitting Objects as Output
- Using Verbose, Warning, and Informational Output
- Comment-Based Help
- Handling Errors
- Are You Ready
-
PowerShell Tool Design
- PowerShell Tools Do One Thing
- PowerShell Tools are Testable
- PowerShell Tools are Flexible
- PowerShell Tools Look Native
- An Example
- Your Turn
- Let’s Review
-
Start with a Command
- Your Turn
- Let’s Review
-
Build a Basic Function and Module
- Start with a Basic Function
- Create a Script Module
- Pre-Req Check
- Running the Command
- Your Turn
- Let’s Review
-
Adding CmdletBinding and Parameterizing
- About CmdletBinding and Common Parameters
- Accepting Pipeline Input
- Mandatory-ness
- Parameter Validation
- Parameter Aliases
- Your Turn
- Let’s Review
-
Emitting Objects as Output
- Assembling the Information
- Constructing and Emitting Output
- A Quick Test
- Your Turn
- Let’s Review
-
An Interlude: Changing Your Approach
- The Critique
- Our Take
- Summary
-
Using Verbose, Warning, and Informational Output
- Knowing the Six Channels
- Adding Verbose and Warning Output
- Doing More With Verbose
- Informational Output
- Your Turn
- Let’s Review
-
Comment-Based Help
- Where to Put Your Help
- Getting Started
- Going Further with Comment-Based Help
- Broken Help
- Your Turn
- Let’s Review
-
Handling Errors
- Understanding Errors and Exceptions
- Bad Handling
- Two Reasons for Exception Handling
- Handling Exceptions in Our Tool
- Handling Exceptions for Non-Commands
- Going Further with Exception Handling
- Deprecated Exception Handling
- Your Turn
- Let’s Review
-
Basic Debugging
- Two Kinds of Bugs
- The Ultimate Goal of Debugging
- Developing Assumptions
- Debugging Tool 1: Write-Debug
- Debugging Tool 2: Set-PSBreakpoint
- Debugging Tool 3: The PowerShell ISE
- Debugging Tool 4: VS Code
- Your Turn
- Let’s Review
-
Verify Yourself
- The Transcript
- Our Read-Through
- Our Answer
- How’d You Do
- Part 2: Professional-Grade Toolmaking
-
Going Deeper with Parameters
- Parameter Position
- Validation
- Multiple Parameter Sets
- Value From Remaining Arguments
- Help Message
- Alias
- More CmdletBinding
- A Demonstration
- Your Turn
- Let’s Review
-
Advanced Function Tips and Tricks
- Defining an Alias
- Specify Output Type
- Adding Labels
- Use Your Command Name Programmatically
- ArgumentCompleter
-
Dynamic Parameters
- Declaring Dynamic Parameters
- Using Dynamic Parameters
- Let’s Review
-
Writing Full Help
- External Help
- Using Platyps
- Supporting Online Help
- “About” Topics
- Making Your Help Updatable
- Your Turn
- Let’s Review
-
Unit Testing Your Code
- Starting Point
- Sketching Out the Test
- Making Something to Test
- Expanding the Test
- But Wait, There’s More
- Your Turn
- Let’s Review
-
Extending Output Types
- Understanding Types
- The Extensible Type System
- Extending an Object
- Using Update-TypeData
- Next Steps
-
Advanced Debugging
- Getting Fancy with Breakpoints
- Getting Strict
- Getting Remote
- Let’s Review
-
Command Tracing
- Getting in PowerShell’s Brain
-
Analyzing Your Script
- Performing a Basic Analysis
- Analyzing the Analysis
- Your Turn
-
Controlling Your Source
- The Process
- Tools and Technologies
- Let’s Review
-
Converting a Function to a Class
- Class Background
- Starting Point
- Doing the Design
- Making the Class Framework
- Coding the Class
- Adding a Method
- Making Classes Easy To Use
- Wrapping Up
-
Publishing Your Tools
- Begin with a Manifest
- Publishing to PowerShell Gallery
- Publishing to Private Repositories or Galleries
- Your Turn
- Let’s Review
- Part 3: Controller Scripts and Delegated Administration
-
Basic Controllers: Automation Scripts and Menus
- Building a Menu
- Using UIChoice
- Writing a Process Controller
- Your Turn
- Let’s Review
-
Graphical Controllers in WPF
- Design First
- WinForms or WPF
- WPF Architecture
- Using .NET
- Using XAML
- A Complete Example
- Just the Beginning
- Recommendations
- Your Turn
- Let’s Review
-
Proxy Functions
- For Example
- Creating the Proxy Base
- Modifying the Proxy
- Adding or Removing Parameters
- Your Turn
- Let’s Review
-
Just Enough Administration: A Primer
- Requirements
- Theory of Operation
- Roles
- Endpoints
- Let’s Review
-
PowerShell in ASP.NET: A Primer
- Caveats
- The Basics
- Beyond ASP.NET
- Part 4: The Data Connection
-
Working with SQL Server Data
- SQL Server Terminology and Facts
- Connecting to the Server and Database
- Writing a Query
- Running a Query
- Invoke-Sqlcmd
- Thinking About Tool Design Patterns
- Let’s Review
- Review Answers
-
Working with XML Data
- Simple: CliXML
- Importing Native XML
- ConvertTo-Xml
- Creating native XML from scratch
- Your Turn
- Let’s Review
-
Working with JSON Data
- Converting to JSON
- Converting from JSON
- Your Turn
- Let’s Review
-
Working With CSV Data
- I Want to Script Microsoft Excel
- Know Your Data
- Custom Headers
- Importing Gotchas
- Your Turn
- Let’s Review
- Part 5: Seriously Advanced Toolmaking
-
Tools for Toolmaking
- Editors
- 3rd Party
- PowerShell Community Modules
- Books, Blogs and Buzz
- Recommendations
-
Measuring Tool Performance
- Is Performance Important
- Measure What’s Important
- Factors Affecting Performance
- Key Take-Away
-
PowerShell Workflows: A Primer
- Terminology
- Theory of Execution
- A Quick Illustration
- When to Workflow
- Sequences and Parallels are Standalone Scopes
- Workflow Example
- Workflow Common Parameters
- Checkpointing Workflows
- Workflows and Output
- Your Turn
- Let’s Review
-
Globalizing Your Tools
- Starting Point
- Make a Data File
- Use the Data File
- Adding Languages
- Defaults
- Let’s Review
-
Using “Raw” .NET Framework
- Understanding .NET Framework
- Interpreting .NET Framework Docs
- Coding .NET Framework in PowerShell
- Loading Assemblies
- Wrap It
- Your Turn
- Let’s Review
-
Scripting at Scale
- To Pipeline or not
- Foreach vs ForEach-Object
- Write-Progress
- Leverage Remoting
- Leverage Jobs
- Leverage Runspaces
- Design Considerations
- Your Turn
- Let’s Review
-
Scaffolding a Project with Plaster
- Getting Started
- Plaster Fundamentals
- Invoking a Plaster Template
- Creating a Plaster Module Template
- Creating a Plaster Function Template
- Integrating Plaster into your PowerShell Experience
- Creating Plaster Tooling
-
Adding Auto Completion
- ValidateSet
- Argument Completer Attribute
- Advanced Argument Completers
- Your Turn
- Let’s Review
-
Adding Custom Formatting
- Format.ps1xml
- Define a TypeName
- Defining a View Definition
- Update-FormatData
- New-PSFormatXML
- Adding to a Module
- Your Turn
- Let’s Review
-
Adding Logging
- Why Are You Logging
- Logging or Transcript
- Structured vs Unstructured
- Write-Information
-
Toolmaking Tips and Tricks
- Format Code
- Part 6: Pester
- Why Pester Matters
-
Core Pester Concepts
- Installing Pester
- What is Pester
- Pester’s Weak Point
- Understand Unit Testing
- Scope
- Sample Code
- New-Fixture
- Writing Testable Code
- What to Test
- Describe Blocks
-
Context Blocks
- BeforeEach and AfterEach
- It Blocks
-
Should and Assertions
- Should Operators
-
Mocks
- Where to Mock
- How to Mock
- Verifiable Mocks
- Parameter Filters
- Mocking the Unmockable
-
Pester’s TESTDRIVE
- Clean Slate and Auto-Cleanup
- Working with Sample Data
- Using TESTDRIVE
-
Pester for Infrastructure Validation
- Spinning Up the Validation Environment
- Taking Actual Action
- Testing the Outcomes of Your Actions
-
Measuring Code Coverage
- Displaying Code Coverage Metrics
- An Example
- Test-Driven Development
- Part 7: PowerShell 7 Scripting
-
PowerShell 7 Scripting Features
- Updating Your Editor
- Ternary Operators
- Chain operators
- Null-Coalescing Assignment
- Null Conditional Operators
- ForEach-Object Parallel
- Using ANSI
-
Cross Platform Scripting
- Know Your OS
- State Your Requirements
- Testing Variables
- Environment Variables
- Paths
- Watch Your Aliases
- Leverage Remoting
- Custom Module Manifests
- Wish List
- Release Notes
Other books by these authors
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earned$12,046,757writing, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
Talking with Tech Leads
Patrick KuaA book for Tech Leads, from Tech Leads. Discover how more than 35 Tech Leads find the delicate balance between the technical and non-technical worlds. Discover the challenges a Tech Lead faces and how to overcome them. You may be surprised by the lessons they have to share.Functional Event-Driven Architecture
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way. Learn to design and develop distributed systems that scale. Identify common design patterns in such systems.
Take your functional programming skills to the next level by joining me in developing a distributed system powered by Apache Pulsar and Fs2 streams, all in Scala 3!
Machine Learning Q and AI
Sebastian Raschka, PhDHave you recently completed a machine learning or deep learning course and wondered what to learn next? With 30 questions and answers on key concepts in machine learning and AI, this book provides bite-sized bits of knowledge for your journey to becoming a machine learning expert.
Getting to Know IntelliJ IDEA
Trisha Gee and Helen ScottIf we treat our IDE as a text editor, we are doing ourselves a disservice. Using a combination of tutorials and a questions-and-answers approach, Getting to Know IntelliJ IDEA will help you find ways to use IntelliJ IDEA that enable you to work comfortably and productively as a professional developer.
The Rails 7 Way
Obie Fernandez, Lucas Dohmen, and Tom Henrik AadlandThe Rails™ 7 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. It illuminates the entire Rails 7 API, its most powerful idioms, design approaches, and libraries. Building on the previous editions, this edition has been heavily refactored and updated.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #5
1500 QUIZ COMMENTATI (3 libri)
3 Books
Tre libri dei QUIZ MMG Commentati al prezzo di DUE! I QUIZ dei concorsi ufficiali di Medicina Generale relativi agli anni: 2000-2001-2003-2012-2013-2014-2015-2016-2017-2018-2019-2020-2021 +100 inediti Raccolti in unico bundle per aiutarvi nello studio e nella preparazione al concorso. All'interno di ogni libro i quiz sono stati suddivisi per... - #6
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #8
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity... - #9
Development and Deployment of Multiplayer Online Games, Part ARCH. Architecture (Vol. I-III)
3 Books
What's the Big Idea? The idea behind this book is to summarize the body of knowledge that already exists on multiplayer games but is not available in one single place.And quite a fewof the issues discussed within this series (planned as three nine volumes ~300 pages each), while known in the industry, have not been published at all (except for...