© Adam Bertram 2020
A. BertramBuilding Better PowerShell Codehttps://doi.org/10.1007/978-1-4842-6388-4_1

1. Do the Basics

Adam Bertram1  
(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

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

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

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

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

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

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

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 copying/pasting.

The fewer place code duplication exists, the simpler the code and the easier that code is to manage.

Further Learning

Don’t Skimp on Security

Many PowerShell developers disregard security implications. It’s not because they don’t care (well, some don’t), it’s because they don’t know any better. Infosec professionals and IT have always been separate wheelhouses. You may not need to know the ins and outs of vulnerability assessments, root kits, ransomware, encryption, or Ttrojans. But you do need to practice common security sense.

Don’t put plaintext passwords in your scripts. Sign your scripts. Don’t set your execution policy to unrestricted. We’ll cover these and more in the security chapter.

Further Learning

Log Script Activity

Record script activity across your organization. PowerShell is a powerful scripting language. PowerShell can automate tasks in no time, but it doesn’t discriminate between test and production. It can also be run by nefarious individuals.

Log script activity. Log it to a text file, a database, or some other data source; just record and audit the activity somehow. Logging is like backups. You might not need them now, but when you do, you’ll be glad you did.

Further Learning

Parameterize Everything

This tip is related to the functions and tools tip. When building scripts and functions, add as many parameters as necessary. Always add a parameter that might one day hold a different value. Never add “static” values to your scripts. If you need to define a value in code, create a parameter and assign it a default value. Don’t assign that value in the code.

Creating parameters allows you to pass different values to your functions or scripts at runtime instead of changing the code.

Further Learning

Limit Script and Function Input

When you open up your scripts to input, limit what can be input as tightly as possible. Be sure to account for as many different ways as possible values may be passed into your code at runtime.

Validate as much input as possible with parameter validation attributes, conditional checks, and so on. Try to never allow a value or type of input into your code you didn’t expect.

Further Learning

Maintain Coding Standards

Come up with a standard and stick to that for everything. Don’t name variables $Var1 in one script and $var1 (note the case) in another. Don’t include a bracket on the same line in one script and the bracket on a new line in the next.

Maintain a consistent coding methodology for everything. If your code is consistent, others (and you) will be able to understand your code much better.

Further Learning

Code in Context

Write a solution specific to context in which it will run. Don’t write a script that expects 10 parameters and give it to your help desk staff. Write a GUI instead. Don’t quickly bang out a script without much thought if it’s going to be used in production.

Worry about performance if the action your script is taking is time sensitive. How you code always depends on the context in which it will run. Don’t assume the code you write and test on your workstation is going to run fine in another environment. Code in the context that the script will run in.

Further Learning

Return Informational Output

Even though you can return anything you want to the output stream, do it wisely. Define what’s verbose, informational, and error output and only show that output in the various streams. Don’t show unnecessary object properties. Instead, use PowerShell formatting rules to hide properties from being seen by default.

Further Learning

Understand Your Code

If you don’t know what a line of code does, remove it or write a Pester test. Understand what each command or function you call is capable of at all times. Don’t simply run a command under a single situation and expect it to run the same way every time.

Test as many scenarios as possible to understand what your code is capable of until various circumstances.

Further Learning

Use Version Control

File names like myscript.ps1.bak and myscript.ps1.bak2 shouldn’t exist. Instead, use tools like Git and GitHub to put your scripts under version control. Version control allows you to audit and roll back changes to your code if necessary.

Version control becomes even more important in a team environment. If you’re serious at all about PowerShell scripting, you must use version control.

Tip Source: https://​twitter.​com/​Dus10

Further Learning

Write for Cross-Platform

PowerShell isn’t just on Windows anymore. PowerShell Core is cross-platform and so should be your scripts. If you ever see a time when your scripts need to run on other operating systems, account and test for that now.

If you’re sharing scripts via the PowerShell Gallery or some other community repository, cross-platform is especially important. Don’t let others find out the hard way your script only runs on Windows.

Further Learning

Write for the Next Person

Be sure other people understand your code. Write your code (and comments) in a clear, concise manner. A layperson should be able to look at your code and understand what it’s doing.

Don’t get fancy just because you can. Don’t use aliases. Instead, write understandable code, include detailed help content, and comment code heavily. Ensure the next person can easily digest your code. You never know. That next person might be you!

Further Learning

Use Visual Studio Code

You can’t get away with a text editor anymore. Your code is too important to sloppily throw together and hope that it runs in a terminal. Using an integrated development environment (IDE) is a must if you want your code to be taken seriously. Use Visual Studio Code with the PowerShell extension. You’ll get all the benefits of a full ISE, linting functionality, autocompletion, and more.

Further Learning

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.173.112