newsletter banner

ISSUE 20.29.F • 2023-07-17 • Text Alerts!Gift Certificates
You’re reading the FREE newsletter

Susan Bradley

You’ll immediately gain access to the longer, better version of the newsletter when you make a donation and become a Plus Member. You’ll receive all the articles shown in the table of contents below, plus access to all our premium content for the next 12 months. And you’ll have access to our complete newsletter archive!

Upgrade to Plus membership today and enjoy all the Plus benefits!

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


ADVERTISEMENT
Hive
We help teams move faster

The first project management platform built for users by users.


WINDOWS

Why PowerShell?

Bruce Kriebel

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

  • @echo off
  • for %%i in (1,2,3,4,5,6,7,8,9,10) DO Echo. Hello there
  • exit

PowerShell

  • For ($Cntr = 0; $Cntr ‑lt 10; Cntr++) {“Hello there”}

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.

CMD file list script
Figure 1. A relatively simple file-listing script, along with its output

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).

PowerShell version
Figure 2. PowerShell version of the script shown in Figure 1, along with its output

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.

Parsing command text output
Figure 3. CLI commands output text which must be parsed.

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.

Get-Help
Figure 4. Get-Help can retrieve a list of all networking-related CmdLets.

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 cmdlet-name -full

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:

  • Get-ChildItem | Get-Member

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).

  • Clear‑Host
  • # *** Note the space between the dot (period) and the G *** below
  • . G:\BekDocs\Scripts\Functions\Get-FileMetaDataReturnObject.ps1
  • $StartTime = Get-Date
  • $Folder    = ‘\\MYBOOKLIVE\CMShared\NAS‑Pictures\2017 Italy’
  • $Metadata  = Get-FileMetaData -folder (Get-ChildItem “$Folder
  •   -Recurse -Directory).FullName
  • $EndTime   = Get-Date
  • “Files Processed: $($MetaData.Count)”
  • “Elapsed Processing Time: $($EndTime – $StartTime)”

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.

Visual progress bar
Figure 5. A simple, visual progress bar

Visual dialog
Figure 6. A full menu environment in a dialog

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.

Talk Bubbles Join the conversation! Your questions, comments, and feedback
about this topic are always welcome in our forums!

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.


ADVERTISEMENT
Pier 1


Here are the other stories in this week’s Plus Newsletter

ONENOTE

Author

Block malicious OneNote attachments without blocking your work

By Mary Branscombe

Making PCs more secure is a continuous cycle of improving security in one area, such as Windows itself, so attackers move on to another avenue of attack.

They go after PDFs, browsers, and — perennially — Office documents, usually through macros.

In each case, Microsoft typically creates a fix for the specific attacks first, then a defense against that category of attacks, and then deeper protections that might make more significant changes to the underlying feature used as an attack vector.

FREEWARE SPOTLIGHT

Deanna McElveen

Universal USB Installer — because flash drives are cheap

By Deanna McElveen

In the immortal words of John Cleese, “And now for something completely different.”

You are here because you love Microsoft Windows (maybe “love” is too strong a word), but that doesn’t mean you can’t dabble in other operating systems.

Universal USB Installer is a free utility by Pen Drive Linux that allows you to easily download and create bootable flash drives for a gazillion operating systems and other bootable tools.

PATCH WATCH

Susan Bradley

Patch testing isn’t easy

By Susan Bradley

No matter who the vendor is, bugs occur.

By the time you read this, Apple will have already re-released its rapid security patches for iOS, iPadOS (16.5.1), and MacOS Ventura (13.4.1). The patches dealt with side effects impacting Facebook, Instagram, WhatsApp, Zoom, and various other websites.

The bug release fixed a WebKit vulnerability that was being exploited in the wild. If you don’t use Safari as your default browser, or if you don’t use the impacted apps, I hope you just did the “sit tight and wait for a re-release” thing.


Know anyone who would benefit from this information? Please share!
Forward the email and encourage them to sign up via the online form — our public newsletter is free!


Enjoying the newsletter?

Become a PLUS member and get it all!

RoboForm box

Don’t miss any of our great content about Windows, Microsoft, Office, 365, PCs, hardware, software, privacy, security, safety, useful and safe freeware, important news, analysis, and Susan Bradley’s popular and sought-after patch advice.

PLUS, these exclusive benefits:

  • Every article, delivered to your inbox
  • Four bonus issues per year, with original content
  • MS-DEFCON Alerts, delivered to your inbox
  • MS-DEFCON Alerts available via TEXT message
  • Special Plus Alerts, delivered to your inbox
  • Access to the complete archive of nearly two decades of newsletters
  • Identification as a Plus member in our popular forums
  • No ads

We’re supported by donations — choose any amount of $6 or more for a one-year membership.

Join Today buttonGift Certificate button

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.