Building Better PowerShell Code: Applying Proven Practices One Tip at a Time
By Adam Bertram
()
About this ebook
Learn to write better PowerShell code via short, example-driven tips. This book covers tips to make your PowerShell scripts faster and easier to read all while following proven best practices. Written by a six-time Microsoft MVP and one of the first Microsoft PowerShell MVPs with over a decade of PowerShell experience, Building Better PowerShell Code gives you easily digestible tips you can begin using immediately.
The book starts with an overview of some of the most important tips the author can muster which segues into a deeper dive with dozens of examples throughout the book. It takes you through tips such as using community modules, writing better comments, thinking of PowerShell functions as building blocks, and more. You will also see how to use parameters the right way and how to create simple logging code to easily record script activity. You will learn not only how to write better code, but also how to implement some mindset tricks, such as being explicit and specific with code and how to write code that reads well. You’ll get into error handling and also how to make your scripts more secure. Finally, you’ll examine the concept of building PowerShell tools and how to build scripts for speed.Other tips and best practices include:
- Building Pester tests
- Improving performance through parallel processing
- Writing cross-platform scripts
- Using filtering properly
After reading this book and applying these tips, you will have an expert coding mindset and be able to build PowerShell code that’s efficient, readable, and compliant with many best practices.
What You Will Learn
- Implement error handling
- Create a logging function
- Use regular expressions to search strings Implement parallel processing
Who This Book Is For
PowerShell script developers.
Related to Building Better PowerShell Code
Related ebooks
Complete Guide to Test Automation: Techniques, Practices, and Patterns for Building and Maintaining Effective Software Projects Rating: 0 out of 5 stars0 ratingsPowerShell for Beginners: Learn PowerShell 7 Through Hands-On Mini Games Rating: 0 out of 5 stars0 ratingsWindows PowerShell for .NET Developers - Second Edition Rating: 4 out of 5 stars4/5Pro PowerShell for Amazon Web Services Rating: 0 out of 5 stars0 ratingsPractical PowerShell Security and Compliance Center Rating: 0 out of 5 stars0 ratingsVisual Studio Condensed: For Visual Studio 2013 Express, Professional, Premium and Ultimate Editions Rating: 0 out of 5 stars0 ratingsPowerCLI Essentials Rating: 0 out of 5 stars0 ratingsMastering Windows PowerShell Scripting Rating: 4 out of 5 stars4/5Learning PowerShell DSC Rating: 0 out of 5 stars0 ratingsPractical PowerShell Exchange Online Rating: 0 out of 5 stars0 ratingsBeginning x64 Assembly Programming: From Novice to AVX Professional Rating: 0 out of 5 stars0 ratingsConfigMgr - An Administrator's Guide to Deploying Applications using PowerShell Rating: 5 out of 5 stars5/5PowerShell and Python Together: Targeting Digital Investigations Rating: 0 out of 5 stars0 ratingsEssential ASP.NET Web Forms Development: Full Stack Programming with C#, SQL, Ajax, and JavaScript Rating: 0 out of 5 stars0 ratingsCyber Security on Azure: An IT Professional’s Guide to Microsoft Azure Security Rating: 0 out of 5 stars0 ratingsUsing and Administering Linux: Volume 3: Zero to SysAdmin: Network Services Rating: 0 out of 5 stars0 ratingsLearn dbatools in a Month of Lunches: Automating SQL server tasks with PowerShell commands Rating: 0 out of 5 stars0 ratingsPowerShell in Depth Rating: 0 out of 5 stars0 ratingsHTML5 and JavaScript Projects: Build on your Basic Knowledge of HTML5 and JavaScript to Create Substantial HTML5 Applications Rating: 0 out of 5 stars0 ratingsLearn Windows IIS in a Month of Lunches Rating: 0 out of 5 stars0 ratingsWindows Performance Analysis Field Guide Rating: 4 out of 5 stars4/5PowerShell and WMI Rating: 0 out of 5 stars0 ratingsArchitecting CSS: The Programmer’s Guide to Effective Style Sheets Rating: 0 out of 5 stars0 ratingsMicrosoft SharePoint 2013 Disaster Recovery Guide Rating: 0 out of 5 stars0 ratingsWPF in Action with Visual Studio 2008: Covers Visual Studio 2008 Service Pack 1 and .NET 3.5 Service Pack 1! Rating: 0 out of 5 stars0 ratingsPro SQL Server 2019 Administration: A Guide for the Modern DBA Rating: 0 out of 5 stars0 ratingsDeveloping Applications with Azure Active Directory: Principles of Authentication and Authorization for Architects and Developers Rating: 0 out of 5 stars0 ratingsLearn Azure in a Month of Lunches Rating: 0 out of 5 stars0 ratingsNetwork Re-engineering: Foundations of Enterprise Computing Rating: 0 out of 5 stars0 ratingsBeginning Git and GitHub: A Comprehensive Guide to Version Control, Project Management, and Teamwork for the New Developer Rating: 0 out of 5 stars0 ratings
Programming For You
Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5Game Development with Unreal Engine 5: Learn the Basics of Game Development in Unreal Engine 5 (English Edition) Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsPython for Beginners: Learn the Fundamentals of Computer Programming Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Learn HTML Programming in 7 Days: Ultimate Beginners Guide to Build and Design Your Own Website Rating: 4 out of 5 stars4/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsData Structures and Algorithm Analysis in Java, Third Edition Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratings
Reviews for Building Better PowerShell Code
0 ratings0 reviews
Book preview
Building Better PowerShell Code - Adam Bertram
© Adam Bertram 2020
A. BertramBuilding Better PowerShell Codehttps://doi.org/10.1007/978-1-4842-6388-4_1
1. Do the Basics
Adam Bertram¹
(1)
Evansville, IN, USA
When it comes to code, there are a lot of opinions out there about best practices.
What one developer thinks is a must, another will refute it. But these disagreements typically happen around specific, nuanced situations like tabs vs. spaces and if a curly brace should go on a new line.
There are larger categories of tips and best practices that are universal. Everyone can agree on broad tips like write tests,
make code reusable,
and don’t store passwords in clear text.
In this chapter, we’re going to hit those broad strokes. We’re going to cover the basic truths that almost everyone can agree on.
In the later chapters, we’ll dive deeper into each of these areas to provide more specific tips the community and I have come up with.
Without further ado, let’s get to the tips!
Plan Before You Code
Don’t automatically jump into coding. Instead, take a little bit of time to do a back of the napkin
plan on what your code will do. Scaffold out code in comments briefly outlining what the code will do in those spots.
Write pseudocode. The practice of writing pseudocode will take your brain through the mental steps of what you need to do.
Further Learning
How to Write a Pseudocode?
Don’t Reinvent the Wheel
Leverage the hard work of others. Don’t completely write a new solution if one already exists. Issue pull requests to existing open source projects if an existing PowerShell module doesn’t quite fit your needs. Don’t fork it and build your own.
Look to the PowerShell Gallery first before embarking on a new script. Someone may have already solved that problem.
Further Learning
Get Started with the PowerShell Gallery
Build Functions As Building Blocks
As you begin to build more complex PowerShell code, begin to think in functions, not lines of code. As you write code, consider if what you’re writing could stand on its own. Consider what the default commands in PowerShell do already. Get-Content reads a text file. Test-Connection checks the status of a network connection. Copy-Item copies a file.
If a script does more than one thing,
consider breaking it up into one or more functions. If you begin to collect a library of functions, create a module.
Further Learning
Building Advanced PowerShell Functions and Modules
Build Reusable Tools
Similar to the Build Functions As Building Blocks
tip, build PowerShell tools, not code. Focus on building reusable scripts, functions, or modules that you can reuse consistently. You should strive to build a library of tools that can be called from other code.
Instead of rewriting code over and over again, you should naturally begin to write code that calls tools. Eventually, you’ll find the majority of your code will be making calls to your tools rather than re-creating the wheel.
Further Learning
Learn PowerShell Toolmaking in a Month of Lunches
Don’t Focus Purely on Performance
Jeffrey Snover, the father of PowerShell, once said that (paraphrasing) PowerShell was meant for humans, not computers. It was built not for blazing performance but to be human readable. It was built to be approachable for non-developers, the IT admins that need to automate tasks but can’t and would rather not develop software applications.
If you’re trying to eke out every last bit of speed from a PowerShell script for no reason other than to satisfy your own OCD tendencies, you’re doing it wrong.
Further Learning
Writing PowerShell Code for Performance
Build Pester Tests
If you build scripts that make their way into production, always include Pester tests with it. Pester tests:
Ensure that your code (at all angles) works
Allow you to make changes and confirm new bugs weren’t introduced
Help you trust your code instead of being afraid you’re going to break it by introducing changes
Build Pester unit tests to test your code. Build Pester integration/acceptance/infrastructure tests to confirm the code you wrote changed what you expected.
Further Learning
The Pester Book
Implement Error Handling
Never let your code throw an exception you didn’t account for. Use $ErrorActionPreference = 'Stop' religiously to ensure all errors are hard-terminating errors. Wrap all code in try/catch blocks and handle thrown exceptions. Don’t leave any possibility for your code to exit without you already expecting it.
Further Learning
The Big Book of PowerShell Error Handling
Build Manageable Code
Build code for the future. Build PowerShell code that won’t leave you wondering WTF this thing does a year from now. Ensure your code can be managed in the long term. Practice the DRY (don’t repeat yourself) principle. Write code once and refer to it rather than