In this issue WINDOWS: Why PowerShell? Additional articles in the PLUS issue ONENOTE: Block malicious OneNote attachments without blocking your work FREEWARE SPOTLIGHT: Universal USB Installer — because flash drives are cheap PATCH WATCH: Patch testing isn’t easy
WINDOWS Why PowerShell?
By Bruce Kriebel For nearly 50 years, we’ve all been using the commands that originated from MS-DOS command line interpreter (CLI). This wasn’t a bad thing. Even when Windows came along, Microsoft provided a means to get to the CLI (the program cmd.exe) and continued to flesh out its capabilities. I’ll bet nearly everyone reading this has written a simple batch file using those commands. But there’s a better alternative. PowerShell is a “shell language.” Here’s Wikipedia’s definition of shell: A shell is a computer program that exposes an operating system’s services to a human user or other programs. In general, operating system shells typically use either a command line interface (CLI) or graphical user interface (GUI), depending on a computer’s role and particular operation. It is called a shell because it is the outermost layer around the operating system. Windows is a GUI shell, and so is the Windows command prompt (CLI). So why the need for PowerShell when people already have — and know how to use — the command prompt? That’s what we will explore here, as we examine the key reasons to use PowerShell instead of the CLI. Readability
To begin, let’s take a look at CLI and PowerShell versions of the world’s most famous introductory computer science program, “Hello World,” with a slight variation. We’ll have it say hello ten times. Command prompt
PowerShell
For something this simple, determining readability is probably in the eye of the beholder. Those with decades of experience with CLI — or basic batch files (.bat) — will probably think that version is easy to read; for that reason, I’d give it a readability score of 95%. Those with programming experience in languages such as C or JavaScript will recognize the syntax of the PowerShell version and consider it straightforward. Generally speaking, I consider it easier to read than the CLI version, especially because it’s just one line. Therefore, it earns a readability score of 99%. Let’s try something a bit more complex. The next example reads a directory and displays information on files that are larger than 4,000 bytes, sorted by file size in descending order. Figure 1 shows the CLI version.
Trying to figure out what this batch file is attempting to do is quite a task, even for an experienced batcher! Of course, the help information provided by each command can provide what’s needed to figure it all out. This is a little batch file I’ve used for years, so old that it required changes because the DIR command is slightly different today. The script illustrates a key problem with batch files. The individual commands were designed to be typed manually, with spartan syntax. I’m being generous in giving this script a readability score of 25%. Let’s see whether PowerShell is any better (Figure 2).
Now, isn’t the PowerShell more readable, even for those who don’t know that Get‑ChildItem is the PowerShell equivalent of DIR? I’ll admit that there are some syntactic oddities with PowerShell, but they become second nature quickly. I give it a readability score of 90%. As shown in this example, PowerShell uses the vertical bar (|) for “piping.” This is an important feature in PowerShell. Commands such as Get‑ChildItem produce output, which would ordinarily be displayed. When the vertical bar is encountered, the output is instead used as input to the next command. In the first two parts of the pipe above, the output from Get‑ChildItem is sent to Sort-Object, which sorts it. The output is once again piped to the last part, which conditionally displays the items found. Capability
PowerShell truly puts some major distance between itself and the Command Prompt where capability is concerned. For one thing, PowerShell has a much richer set of commands than the significantly older command line, which means you can do things that are tedious, hard, or even impossible with CLI. For another, once you learn the basics it will be much easier to use PowerShell. Why? Because PowerShell returns information in the form of “Objects,” which can easily be processed by subsequent commands. That’s why the Sort-Object command in Figure 2 doesn’t require specific information about the input it’s receiving; it can just examine the object and figure it out. CLI commands always output text, which means the script must be written to parse the text in order to extract the needed data. As shown in Figure 3, the parsing is largely positional.
Now you can see where those variables (named by a letter preceded by two percentage signs in Figure 1) come from — they correspond to the red letters shown in Figure 3. But in PowerShell, the elements in an object have meaningful names, such as LastWriteTime, Length, and Name. PowerShell also provides a vast array of already written code to give you access to a plethora of Windows information and functionality. These pieces of code are called CmdLets. Our example includes such CmdLets as Get‑ChildItem, Sort‑Object, and ForEach‑Object. CmdLets use the naming convention verb‑noun. Discoverability
You can easily discover and learn about the available CmdLets by using Get‑Help. For example, you can enter Get-Help *Net* to find all CmdLets related to networking, as shown in Figure 4.
The list is much longer than shown in Figure 4 — it actually returns 331 results. To get help about any one of them, use this command:
Get‑Help will then return the syntax, offer explanations of available arguments, and provide examples of the CmdLet’s usage. To discover the properties a CmdLet returns, simply pipe the output of the CmdLet to the Get‑Member CmdLet, as in:
If you can’t find a CmdLet to accomplish your task, you can write your own functions just as you would with any other programming language. CmdLets are just built-in functions. Maintainability
Of course, maintainability is closely related to readability. If you can’t quickly read the code you wrote six months ago, you’ve got a problem. You’ll waste time trying to figure out exactly how the code is functioning before you can even attempt to change it. Yes, you should always comment your code extensively. But the REM statement in a batch file is awkward at best and must be repeated on each line of a multiline comment. PowerShell’s comment syntax is more like that of a traditional programming language. But because PowerShell is inherently more readable, it will probably require less extensive commenting. Looking back at the second example under Readability above, you can quickly see the lack of need for comments in the PowerShell code. This contrasts sharply with both the lack of and need for comments in the batch code. Here is another area where PowerShell shines. Because the naming convention of CmdLets and the capability to write your own CmdLets allow a high degree of granularity to your code, you can quickly zero in on the area causing the problem or needing to be updated, without worrying much about the rest — except where it uses the output of the changed code. Reusability
When you’re writing in PowerShell, you’ll often see code that gets repeated. You can easily take such code and put it into a user-defined CmdLet (i.e., function), which can then be used in other scripts. You have the choice of copying them into your current script or, to keep scripts shorter, “dot source” them (the line highlighted in red below).
The script loads the file Get-FileMetaDataReturnObject.ps1 and then uses a function defined in that file, Get-FileMetaData. In most languages, the “dot source” is called an “include.” Although it’s possible to call one batch file from another, it’s a kludge from another era that provides no support for user-defined functions. PowerShell is a modern language in that respect. GUIability (I made that up, but it’s real)
The ability to add a graphical user interface (GUI) to your scripts is one of PowerShell’s strengths. Although there are third-party add-ons that provide the same capability to batch files, there is no comparison. Obviously, a GUI can make your scripts much easier to use — especially important if your scripts will be used by others. Two examples are shown in Figures 5 and 6.
PowerShell provides the user with a powerful scripting (shell) language that provides extensive and extensible access to the inner workings of Windows. Oops, that’s not entirely correct. Windows PowerShell was originally a Microsoft product for Windows XP SP2 (who knew?) but not built in. Windows PowerShell 2.0 was incorporated into Windows 7, and version 5.1 is still included in modern Windows but no longer being developed. On August 18, 2016, PowerShell Core was released as an open‑source project and gained cross-platform capabilities. Besides Windows, it is now available for macOS 10+, Ubuntu 14+, and many other flavors of Linux. The original PowerShell had its own integrated scripting environment (ISE) called Windows PowerShell ISE, a handy development and debugging tool with a relatively easy-to-use interface. Its development stopped when PowerShell Core became available. Instead, Microsoft developed an extension for Visual Studio Code (VSC) called simply PowerShell. Both VSC and the extension are free downloads. The extension closely mimics the old ISE and has better performance. Microsoft is heavily committed to VSC and PowerShell, so we can expect long-term support and development of these tools. I’m not suggesting that a transition from batch files based upon the CLI (now a half-century old) to PowerShell will be quick. The difference between the two can be jolting. However, learning the basics is not that hard. Once that foundation is laid, you’ll find PowerShell far more powerful and useful than the command line ever was.
Bruce Kriebel (aka RetiredGeek) started programming by taking a Fortran course in 1974 and never looked back. The proud owner of a very early Radio Shack TRS-80 Model I, he helped lead a three-lettered agency into the personal computer age. If it’s a PC productivity program, he has probably used and programmed it.
The AskWoody Newsletters are published by AskWoody Tech LLC, Fresno, CA USA.
Your subscription:
Microsoft and Windows are registered trademarks of Microsoft Corporation. AskWoody, AskWoody.com, Windows Secrets Newsletter, WindowsSecrets.com, WinFind, Windows Gizmos, Security Baseline, Perimeter Scan, Wacky Web Week, the Windows Secrets Logo Design (W, S or road, and Star), and the slogan Everything Microsoft Forgot to Mention all are trademarks and service marks of AskWoody Tech LLC. All other marks are the trademarks or service marks of their respective owners. Copyright ©2023 AskWoody Tech LLC. All rights reserved. |