Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
PowerShell 7 Workshop
PowerShell 7 Workshop

PowerShell 7 Workshop: Learn how to program with PowerShell 7 on Windows, Linux, and the Raspberry Pi

By Nick Parlow
$35.99 $24.99
Book Feb 2024 468 pages 1st Edition
eBook
$35.99 $24.99
Print
$44.99
Subscription
$15.99 Monthly
eBook
$35.99 $24.99
Print
$44.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

PowerShell 7 Workshop

Introduction to PowerShell 7 – What It Is and How to Get It

Quite simply, PowerShell is a time machine. Not a science-fiction time machine where you get to go back in time and meet your own grandfather, but a real, practical one. If you put in a small amount of time, then PowerShell, like any simple machine, will act as a force multiplier; it will produce very much more time for you. To use a metaphor, it’s a time hammer, and the hours you put into learning PowerShell will save you tens or hundreds of times as many hours once you start putting the knowledge to use.

This chapter is a general introduction to PowerShell 7. It’s going to give you some context about PowerShell and get you up and running. You’re going to learn what you can do with it and some typical use cases. We’ll be installing PowerShell, and you’ll get to choose one or more ways of doing that. Once we’ve got it installed, we’ll go through how you run commands (called cmdlets), and how you can find cmdlets to run. Finally, and quite importantly, we’ll work through how to get help, both with cmdlets and with PowerShell topics and concepts.

In this chapter, we’re going to cover the following main topics:

  • What is PowerShell 7?
  • What is PowerShell 7 used for?
  • Getting PowerShell 7
  • Running PowerShell 7
  • Getting help

Technical requirements

To follow along with this chapter, you will need an internet connection and an operating system. If you’re using Linux or macOS, the installation instructions can be found in Chapter 14, PowerShell 7 for Linux and macOS, so skip the detailed installation instructions in the How to get PowerShell 7 section, in this chapter.

This chapter assumes that you will be using Windows 10 (version 1709 or later) running on standard 64-bit x86 architecture. If you’re not sure whether that’s what you have, don’t worry, it probably is. If you are one of life’s worriers, go to the Windows search bar and type msinfo32, then press Enter. The System Information application will open, and under System Summary, there will be three relevant lines:

  • OS Name: Hopefully Microsoft Windows 10 of some flavor; PowerShell 7.3 is available on all currently supported versions of Windows.
  • Version: You want a build number higher than 16299.
  • System Type: Probably x64-based PC.

The following screenshot shows how it should look under System Summary:

Figure 1.1 – Typical information from the System Information application (msinfo32)

Figure 1.1 – Typical information from the System Information application (msinfo32)

If you’re using Windows 11, then good for you; you won’t need to do some of the things we’ll be talking about as Windows 11 comes with some extras.

What is PowerShell 7?

PowerShell is a scripting language and an alternative to the command-line interface. PowerShell is an automation tool consisting of (at least) three parts:

  • A shell, like the Command Prompt in Windows or the Terminal in Linux or macOS
  • A scripting language
  • A configuration management framework called Desired State Configuration (DSC)

In practice, when we talk about PowerShell, we’re usually talking about the scripting language. Usage of the shell is largely intuitive to the user, as we’ll see, and while we’ll talk about DSC later, in my experience, most people don’t use it as much as they should.

The first version of PowerShell grew out of a project called Monad, which was an attempt by Jeffrey Snover to replicate Unix tools on Windows. He realized that one of the fundamental drawbacks of Unix tools is that they output a bytestream (usually text), and so a lot of effort is wasted on searching, formatting, and extracting the output of commands before you can act on that output. Monad was written to output objects that could be input straight into another command. We’ll cover this in more detail when we get to Chapter 4, PowerShell Variables and Data Structures. PowerShell 1.0 was released in 2006, but in my opinion, it didn’t really take off until PowerShell 2.0 was released in 2009, and Microsoft started re-engineering the administrative interfaces of major pieces of software such as Exchange Server 2010 to make use of it. Other opinions are available.

At the time of writing, there are two main flavors of PowerShell: Windows PowerShell, which comes bundled with both server and desktop versions of Windows, and PowerShell 7, which must be downloaded and installed. The latest (and allegedly final) version of Windows PowerShell, v5.1, is built on .NET Framework 4.5, the proprietary software framework that is bundled with Windows and underpins many of Microsoft’s products. PowerShell 7.0 was built on .NET Core 3.1, a simplified, open source implementation of .NET. However, since version 7.2, PowerShell has been built on .NET 6.0. This unified version of .NET is a replacement for both .NET Framework and .NET Core, and was released in November 2020.

Because of the fundamental differences between Windows PowerShell 5.1 and PowerShell 7.x, there can be some differences in how they work on the Windows platform. These will be discussed in Chapter 13, Working With PowerShell 7 and Windows.

We’ll find it useful to summarize some of the key differences in the following table:

Parameters

Windows PowerShell

PowerShell 7.2

Platform

x64, x86 only

x64, x86, arm32, arm64

OS

Windows

Windows, Linux, macOS

.NET Version

.NET Framework 4.5

.NET 6.0

License Type

Proprietary

Open source

No. of Native Commands

1588 (in vanilla Windows 10)

1574 (in vanilla Windows 10)

290 (in Ubuntu 20.04)

Table 1.1 – Some differences between Windows PowerShell and PowerShell 7

In this section, we have covered what PowerShell is, and how it differs from Windows PowerShell. In the next section, we’ll look at why PowerShell 7 exists and see what makes it special.

What is PowerShell 7 used for?

PowerShell is for getting things done quickly. It’s for when you need a relatively short piece of code for something that you can reuse and repurpose easily to do something else. It’s for when you don’t want to spend months learning a language, then more months writing thousands of lines of code. The language can be used in at least four ways:

  • You can input single lines of code in the shell, as you would at the Windows Command Prompt or the Linux Terminal. This is great if you need to check a value, accomplish a single task such as rebooting a remote computer, or grab a log file.
  • You can write a script, such as a Bash script in Linux or a batch file for Windows, that accomplishes multiple subtasks, such as gathering event logs and performance information from several machines and compiling them into a single HTML report.
  • If you write a lot of scripts or need to accomplish something more complex, you can use PowerShell as a procedural programming language with multiple packaged scripts that each describe a single function and are called by a master script.
  • You can use it as an object-oriented programming language and package a whole application that can be redistributed and run by anyone with PowerShell installed.

We’ll be focusing on scripts and procedural programming in this book, as that is how most people use PowerShell. These are very similar; the difference is that in a script, you are using cmdlets that have been written for you, but in procedural programming, you are creating your own cmdlets, either from pre-existing cmdlets or by using the system programming language C#.

Scripting languages versus system programming languages

The PowerShell language is a scripting language. It’s for gluing other applications together quickly and easily – sort of a coding version of Lego. It relies on an underlying interpreter: the PowerShell program. Without PowerShell installed, a PowerShell script can’t run. This is quite similar to other interpreted languages, such as Python, and sits in contrast to system programming languages, such as C or C++, which are compiled into executable files. When you compile a C++ program, it can theoretically run on any compatible machine. There are other differences as well – here are some of the main ones:

  • Interpreted languages are less efficient than compiled languages because each line has to be interpreted before it can run. This means they are slower than compiled programs. There are programming tricks you can use to speed things up, but performing a task in an interpreted language will pretty much always be slower than doing it in a compiled language.
  • Interpreted languages are more efficient than compiled languages in development. They accomplish the same tasks with far fewer lines of code. This means that writing them, debugging them, and reusing them is much quicker. They are also much easier to learn.
  • Interpreted languages can run on multiple architectures. As we’ll see in this book, code written in PowerShell can run on Windows, Linux, or macOS, with minimal tweaking. A program written in C++ for Windows can only run on Windows, or a machine with Windows emulation. It would need to be rewritten and recompiled for a different platform.
  • Interpreted languages produce collaborative reusable programs. With PowerShell (or Python), you produce code that is readable and editable by humans. With a compiled language, you produce a binary file that cannot easily be decompiled into source code for reuse. This means other people can reuse your code for their own purposes. Platforms such as GitHub can be used to distribute your code, other people can contribute to it, improve it, reuse it for their programs, and act in a generally communitarian fashion.

It boils down to this: if you want to write a super-fast first-person shooter game with spectacular graphics, then PowerShell is probably not the language for you. If you want to automate some tasks, simple or complex, then PowerShell is a good choice.

Getting PowerShell 7

In this section, we’ll look at some of the ways to get PowerShell onto your machine, where it goes and why, and how you can control aspects of your installation. This chapter will only cover installation on Windows; for detailed installation on Linux, macOS, and ARM systems, please have a read of Chapter 14, PowerShell 7 for Linux and macOS, or Chapter 15, PowerShell 7 and the Raspberry Pi, and come back for the next two sections of this chapter.

It’s possible to have more than one version of PowerShell running simultaneously on your machine – I usually have three at once: Windows PowerShell, PowerShell 7 (current version), and PowerShell 7 Preview. This is not just for when I’m writing a book – we need to know that the scripts we write will run in different environments and rewrite them if necessary. It’s also useful to be able to control the installation when you’re intending to run PowerShell on a remote machine that may not have it installed yet. Windows PowerShell is included in the Windows operating system and is installed in the \Windows\system32 folder; that’s where it lives, and you can’t move it anywhere else. In contrast, PowerShell 7 can be installed wherever you like, within reason. We’re going to cover the three most common methods of installation:

  • Installation from an .msi file with Windows installer
  • Installation from a .zip file
  • Installation with winget

There are two other methods that we will cover briefly: installing from the Microsoft Store, and installing as a .NET Global tool.

If you want to experiment a little, and you have Windows 10 Pro or Enterprise, then you can enable the Windows Sandbox feature in Control Panel | Programs and Features | Turn Windows features on or off.

This will give you a completely blank, secure Windows environment to play around in. Be careful – when you turn it off, it’s gone for good. The next time you turn it on, all your changes will be lost:

Figure 1.2 – Turning on Windows Sandbox

Figure 1.2 – Turning on Windows Sandbox

Full details of the requirements for running Windows Sandbox can be found here: https://docs.microsoft.com/en-us/Windows/security/threat-protection/Windows-sandbox/Windows-sandbox-overview.

Let’s get started. Make sure you have met the technical requirements listed at the beginning of the chapter.

Installation from an .msi file

All of the official PowerShell distributions can be found on the PowerShell GitHub page at https://github.com/PowerShell/PowerShell:

Figure 1.3 – Get PowerShell from the GitHub page

Figure 1.3 – Get PowerShell from the GitHub page

As you can see, for most operating systems and platforms, there are three types of release: LTS, stable, and preview. LTS stands for Long Term Support. LTS releases come out on a slow cadence, to ensure stability in environments that are risk-averse, and they usually only contain critical security updates and software fixes, not new features. The PowerShell LTS releases are based on the underlying LTS version of .NET. The preview release is the next version of PowerShell. It may have exciting new features, but it will also likely be unstable and have some flaws. Stable releases are updated every month or so and may include new functionality, as well as software fixes and security updates. Each release is supported for six months after the next release.

Let’s go ahead and install the most common release, the stable release for Windows x64:

  1. Browse to the GitHub Releases page for PowerShell here: https://github.com/PowerShell/PowerShell.
  2. Click to download the stable .msi package for Windows x64.
  3. Locate the .msi file in your Downloads folder and run it. This will start the setup wizard.
  4. The first choice you must make is the install location. By default, it will install into a numbered folder under C:\Program Files\PowerShell, where the number matches the major version – in our case, 7. If you are installing a preview version, then the folder will have a -preview suffix. This is a pretty good location, but you may want to put it somewhere else, for example, if you are running multiple versions of PowerShell side by side. Go ahead and accept the default this time:
Figure 1.4 – The default install location

Figure 1.4 – The default install location

  1. Now we get to the Optional Actions menu:
Figure 1.5 – Optional Actions

Figure 1.5 – Optional Actions

There are five options here:

  • Add PowerShell to Path Environment Variable: You will almost certainly want to choose this. With this option enabled, you can start PowerShell from any location. Be aware that if you install a different version side by side, it will overwrite the installation path variable and you will need to manually navigate to the location of pwsh.exe to run this one.
  • Register Windows Event Logging Manifest: You will want to enable this as well. This will create a new Windows Event log called PowerShell Core and start logging PowerShell events to it.
  • Enable PowerShell remoting: Enabling PowerShell remoting will make the machine listen for incoming connections from PowerShell sessions. This is obviously a bit of a security vulnerability, so you should only enable it if you need it and your machine is on a private network. You don’t need to enable it to connect to remote sessions on other machines.
  • Add ‘Open here’ context menus to Explorer: This will allow you to open a PowerShell session in a folder in File Explorer – the PowerShell session will open with the path set to the folder you selected.
  • Add ‘Run with PowerShell 7’ context menu for PowerShell files: This will allow you to right-click a file and open it with PowerShell 7. For reasons we will see later, this might not always be desirable.
  1. After Optional Actions, we come to the Microsoft Update option. You can use Microsoft Update to keep PowerShell updated; this is highly recommended as it can automatically download security patches for you and apply them according to your existing update schedule. Be aware that this setting can be overridden by group policy if you are working in a domain-joined environment. There are two checkboxes; the first enables updates for PowerShell, while the second enables Microsoft Update on the system. Note that unchecking this box only disables Microsoft Update; if your environment uses a configuration manager such as Windows Software Update Services (WSUS) or System Center Configuration Manager (SCCM), then they will still work.
  2. Finally, we’re ready to install by pressing the Install button. This is a short process and should be done in a minute or two. Click Finish, and we’re all set.

There is an alternative to using the GUI. You can run the .msi file from the command line with msiexec.exe, as documented here: https://docs.microsoft.com/en-gb/powershell/scripting/install/installing-powershell-on-Windows?view=powershell-7.2#install-the-msi-package-from-the-command-line.

To silently install PowerShell on Windows Sandbox as you’ve just been shown, you can run the following:

msiexec.exe /package c:\Users\WDAGUtilityAccount\Downloads\PowerShell-7.2.1-win-x64.msi /quiet REGISTER_MANIFEST=1 USE_MU=1 ENABLE_MU=1

Notice that there is no property for enabling or disabling Add PowerShell to Path Environment Variable. If you run the .msi file from the command line, then PowerShell will automatically get added. Because we’ve used the /quiet switch, there is no output to this command, but if it is successful, then you will see PowerShell in your Start menu.

Activity 1

How might you enable the file context menu when installing PowerShell from an .msi file using the command line? (Hint: Check the link in the earlier paragraph to find out.)

Installation from the .zip file

Another popular way to install PowerShell is from the .zip file. With this method, we simply extract the binaries and associated files to a suitable folder. The disadvantage is that the prerequisite checking and options that are available with the .msi install are lost; for instance, you can’t automatically add PowerShell to the PATH environment variable or enable PowerShell remoting. The advantage is that it is much easier to script the installation of PowerShell as part of a DevOps or Infrastructure as Code pipeline, and you can enable other features as part of the script.

In Windows, there’s no native way to install a file from the internet via scripting. You need to either already have PowerShell (which you automatically do in the form of Windows PowerShell on a Windows machine), or install a tool such as curl.

Here’s how you do it with Windows PowerShell:

Invoke-WebRequest https://github.com/PowerShell/PowerShell/releases/download/v7.2.1/PowerShell-7.2.1-win-x64.zip

If you run the preceding cmdlet, then you should see output like this. Notice that it’s an HTTP response, and so a StatusCode result of 200 is good:

Figure 1.6 – Downloading PowerShell 7 with Windows PowerShell

Figure 1.6 – Downloading PowerShell 7 with Windows PowerShell

You can run the entire process like this with four lines of code:

New-Item -Path c:\scratch\myPowershell\7.2 -ItemType Directory
Invoke-WebRequest https://github.com/PowerShell/PowerShell/releases/download/v7.2.1/PowerShell-7.2.1-win-x64.zip -OutFile C:\scratch\myPowershell\7.2\PowerShell-7.2.1-win-x64.zip
Expand-Archive C:\scratch\myPowershell\7.2\PowerShell-7.2.1-win-x64.zip -DestinationPath C:\scratch\myPowershell\7.2\
Remove-Item C:\scratch\myPowershell\7.2\PowerShell-7.2.1-win-x64.zip

Don’t worry too much about the preceding commands – we’ll be covering all of them in due course. In summary, the first line creates a new folder. The second line downloads the .zip package from GitHub to your new folder. The third line unzips everything, making it ready for you to run, and the fourth line removes the downloaded package.

There are two errors you may experience with this. Firstly, you may see a red error message:

Invoke-WebRequest : The request was aborted: Could not create SSL/TLS secure channel"

This is because, by default, Windows PowerShell will use TLS v1.0, and many websites no longer accept this protocol. If you do see this, run the following .NET code and try again:

[Net.ServicePointManager]::SecurityProtocol = "Tls, Tls11, Tls12, Ssl3"

The other error you may see is a message saying this:

Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again

In this case, run the Invoke-WebRequest cmdlet with the UseBasicParsing parameter:

Invoke-WebRequest https://github.com/PowerShell/PowerShell/releases/download/v7.2.1/PowerShell-7.2.1-win-x64.zip -UseBasicParsing

Replace the second line of the script with this line. It’s exactly the same but adds the UseBasicParsing parameter.

Installation with winget

winget, also known as the Windows Package Manager, is a free, open source package manager from Microsoft for Windows Clients. It is bundled with Windows 11 and may be downloaded for Windows 10 via the Microsoft Store. It is similar in functionality to Linux package managers such as APT, YUM, and DNF. It supports .exe, .msi, and .msix packages – you can’t use it to install the .zip release. When you run winget, it searches for, downloads, and installs the PowerShell .msi release of your choice. You do it like this:

  1. First, run a search for PowerShell packages. From the Windows PowerShell Command Prompt, run this line:
    winget search microsoft.powershell

This will return the versions of PowerShell available to winget.

  1. You then need to install a package. I’m choosing to install the preview by running the following:
    winget install --id microsoft.powershell.preview --source winget

And that’s it. There are a few things to note here. Firstly, you’re installing the .msi file, so unless you suppress them, you will see several GUI messages. You can do this with the --silent switch. Unless you are happy with the default choices, you will also need a way to pass parameters to the .msi file you are calling. You can do this with the –-override switch, and then by passing the command-line switches for the .msi package that we looked at before. Secondly, if you have User Access Control enabled, you will need to give permission for PowerShell to be installed. If you’re using the --silent switch, then you won’t see this prompt. If you want to do a silent install, you’ll need to run Windows PowerShell with administrator privileges.

Here’s how the whole install looks if you run it from a Windows PowerShell command line with administrator privileges:

Figure 1.7 – Silently installing PowerShell with winget

Figure 1.7 – Silently installing PowerShell with winget

The main advantage of winget is that it has its own repository for community-created packages; anyone can bundle an app by writing a manifest and uploading it. The repository is secured with Microsoft SmartScreen to stop malicious code from finding its way into the repository. There’s a lot more on winget here:

https://docs.microsoft.com/en-us/Windows/package-manager/winget/.

In summary, you’re not really doing anything with winget that you didn’t do by running msiexec.exe previously, but it’s a bit newer and cooler, has a useful repository, and is slightly easier to use. In a couple of years, we’ll wonder how we ever did without it, especially if they make it available on Windows servers.

Other ways to install

There are two other ways to install PowerShell that we should discuss. Neither is likely to be applicable to us. Firstly, if you have the .NET Software Development Kit (SDK) installed, then we can use that to install PowerShell as a global tool. This is only really useful for software developers, and it doesn’t make much sense to install the SDK just for PowerShell.

The other way you can install PowerShell on Windows is through the Microsoft Store as an app. The big drawback to this method is that Store apps run in a sandbox environment that restricts access to the application’s root folder. This means that several PowerShell features just won’t work properly.

Note

A sandbox is not necessarily the same as Windows Sandbox. The generic term “sandbox” refers to a secure computing environment with separate resources, meaning that whatever is running in there cannot interfere with anything outside the sandbox. Windows Sandbox is a specific example of a generic sandbox.

Running PowerShell 7

The first way everyone runs PowerShell is through the bundled console (remember, PowerShell is not just a language, it’s a shell and a configuration management framework as well). Let’s assume that you installed using the .msi method from before, and you added PowerShell to the PATH environment variable. If you’ve done this, then all you need to do to start PowerShell is type pwsh into the Windows search bar and click on the application. Alternatively, you can right-click the Start menu and type pwsh in the Run box. Or, you could just hold down the Windows key and press R, which would call up the Run box as well.

If you didn’t add PowerShell to the path, you will need to type the full path to the executable pwsh, as in C:\program files\PowerShell\7\pwsh.

The first thing you will notice if you’ve been paying attention to the preceding screenshots or you’ve followed along is that the console window that comes up has a black background. This differentiates it from Windows PowerShell:

Figure 1.8 – Two different versions of PowerShell

Figure 1.8 – Two different versions of PowerShell

If you have installed PowerShell on Linux or macOS, then open a Terminal and type pwsh – the Terminal will switch to a PowerShell prompt.

It is traditional in most programming books that the first thing you do is coax your application to produce the words "Hello World" onscreen, and there’s no reason we should be any different. Type the following into the console and press Enter:

Write-Host "Hello World"

You should get something like this:

Figure 1.9 – Hello yourself

Figure 1.9 – Hello yourself

If you did it, congratulations! You’ve just run your first PowerShell command, or cmdlet, as they are called.

Notice that the console automatically colors things that it recognizes or expects; cmdlets are yellow, strings are blue. It’s also very forgiving – if you had forgotten the inverted commas, then "Hello World" would not have been blue, but PowerShell would have interpreted it correctly anyway.

Note

Be careful with this; while PowerShell is quite clever, it won’t always interpret input the way you hope. It’s best to tell it explicitly what type of input you are giving it. More on this later.

The most likely cause of an error is that you misspelled the cmdlet or didn’t close the inverted commas, as illustrated in the next figure. You’ll see a helpful red error message telling you what you’ve done wrong and suggesting ways to fix it. I have come to cherish these error messages:

Figure 1.10 – Three ways to be wrong

Figure 1.10 – Three ways to be wrong

In the third attempt, I didn’t close the inverted commas, so PowerShell was expecting more input. It told us this with >> on the line below. It also told us that it didn’t think the cmdlet would run as you have written it by coloring the > in the Command Prompt in red.

Note that unlike in some environments, capitalization here doesn’t matter; write-host is functionally the same as Write-Host.

Running PowerShell with administrator privileges

By default, PowerShell will run under the account that launches it, but it will only have standard user privileges. If you need access to your local machine that would normally require administrator privileges, then PowerShell will either fail to run some cmdlets or give you a User Account Control (UAC) prompt. To prevent this, you need to start PowerShell with administrator privileges. There are many ways to do this, but here are two of the most common.

Firstly, you can open the search bar, type pwsh, and then right-click on the PowerShell 7 icon and select Run as administrator:

Figure 1.11 – Starting PowerShell as an administrator

Figure 1.11 – Starting PowerShell as an administrator

The second, slightly more impressive method is to hit the Windows key + R to bring up the Run box, type pwsh, and then hold down Ctrl + Shift + Enter. This will start PowerShell as an admin.

PowerShell clearly shows whether it is running with admin privileges in the window title. Here are two PowerShell sessions running the same cmdlet. The lower window is running with admin privileges:

Figure 1.12 – Sometimes you have to be an admin

Figure 1.12 – Sometimes you have to be an admin

If administrator mode is something you are likely to use a lot, then it’s easiest to just right-click the PowerShell icon when it’s running and select Pin to taskbar. Then you can right-click the pinned icon whenever you need it and select Run as administrator.

Autocomplete

By now, you’re probably getting a little tired of having to type a lot of long and unfamiliar cmdlets in. Let me show you a great feature of the shell: autocomplete. Try this – in your shell, type the following without pressing Enter:

Stop-s

Now press the Tab key. Cool, isn’t it? But it’s not the cmdlet we want. Press the Tab key again. You should now have the Stop-Service cmdlet fully typed. Now, add a space, type -, and press the Tab key again. Keep pressing the Tab key until you’ve gone through all the possible parameters for the Stop-Service cmdlet. Press Esc when you’ve done that.

This is a great way to avoid typing out loads of letters, but it’s also a really good way of checking that what you are doing will work. If autocomplete doesn’t work, then the chances are that the cmdlet, parameter, or option you want isn’t available on this machine.

In the next chapter, we’ll look at some other ways of starting and using PowerShell, but for now, you’re all set with what you need.

Getting help

Now that you’ve installed PowerShell and can start it, you need to do stuff with it. You’re going to need help with that. Happily, PowerShell comes with three useful cmdlets built in: Get-Command, Get-Help, and Get-Member. Each of these cmdlets will tell you useful things and give you guidance. Let’s start with Get-Command.

Get-Command

Get-Command will give you a list of cmdlets. If you type it in just like that, it will give you a list of around 1,500 cmdlets. When you start installing and writing modules, that list will grow significantly. Scrolling through a list of thousands looking for a likely cmdlet is not that efficient. What you need to do is search the list.

Imagine you need to interrogate a particular process that is running on your client. It is likely that a cmdlet for doing that would include the word process somewhere. Go ahead and try typing the following into your shell:

Get-Command *process

You should see something like this:

Figure 1.13 – Searching for relevant cmdlets

Figure 1.13 – Searching for relevant cmdlets

The cmdlet interprets *process as a string and searches for cmdlets that end in process. The * is a wildcard character. Try running it like this:

Get-Command process

You’ll probably get an error in red.

Some of those cmdlets look a bit cryptic, but there are a few that really stand out – Get-Process especially. Try running that. You should see quite a long list of processes and some information about them. Let’s look at a process I know you’re currently running: pwsh. Type the following:

Get-Process pwsh

You should see information for your PowerShell processes:

Figure 1.14 – My PowerShell processes

Figure 1.14 – My PowerShell processes

That’s very nice, but what does it all mean? Let’s look at the next of our three helpful cmdlets: Get-Help.

Get-Help

Running the Get-Help cmdlet is easy; type Get-Help followed by the name of the cmdlet you would like help with:

Get-Help Get-Process

You should then see something like this:

Figure 1.15 – Running Get-Help for the first time

Figure 1.15 – Running Get-Help for the first time

That doesn’t look very helpful. However, if you read the REMARKS section, there’s an explanation. PowerShell doesn’t ship with full help; you need to download and update it. To update the help files, run the following:

Update-Help

It will take a little while to run, and if you have installed some modules, help files may not be available online for all of them, so you will see red error messages, but after a minute or two, it should finish, and you can then try getting help for Get-Process again.

Get-Help Get-Process

PowerShell is quite biased toward the en-US culture. Culture here refers to a specific meaning within .NET and associated programs such as PowerShell; it’s equivalent to locale in other systems and refers to the settings specific to a language, number format, and date-time format. If your environment is not set to en-US, then it may not download all of the relevant help files. If you find you’re not getting everything, try running this line:

Update-Help -UICulture en-US

Then, try again. This is something that particularly affects Linux installations.

You should see a lot more information, including a one-line synopsis and a detailed description. If that’s not enough, then in the REMARKS section, there will be some other ways of getting even more information about the cmdlet. Try running this:

Get-Help Get-Process -Detailed

You will see more detailed information, including examples of how to use the cmdlet. To see all the information available, use this:

Get-Help Get-Process -Full

You will see everything in the help file, including the extremely useful NOTES section, which, for this cmdlet, will tell you how to interpret some of the values in the output.

There is one other useful way to run Get-Help for a cmdlet, using the -online parameter:

Get-Help Get-Process -Online

This will produce the web page for the cmdlet in your default browser; it gives the same information as when you use the -Full parameter.

About files

Get-Help doesn’t just help you with cmdlets; you can also get lots of useful information about PowerShell concepts in a special set of files called ABOUT TOPICS. At the time of writing, there are over 140 of them. There’s lots of information in these files about programming concepts, constructs, and common queries such as logging for both Windows and non-Windows environments. Have a look yourself by running the following:

Get-Help about*

Let’s have a look at one of the files:

Get-Help about_Variables

You should see lots of interesting information about how variables are used in PowerShell.

You can also use full-text search with Get-Help. If the word you are looking for is not in the help file’s name, then the text of the files will be searched. This takes a little longer but can often be worth it. Try entering the following:

Get-Help *certificate*

Make a mental note of the results you get. Now, try entering certificates, plural:

Get-Help *certificates*

You’ll get a different set of results. The first set finds help files with certificate in the filename. When Get-Help produces the second set, it can’t find any files with certificates in the name, so it does a full text search. Note that if the search term does occur in a filename, then the full text search won’t be carried out.

The only downside I find with these files is that there is some expectation for you to be knowledgeable about everything in PowerShell except the topic in question. For example, ABOUT_VARIABLES mentions the scope variable in the first few paragraphs. Nonetheless, if you need to know how something works quickly, then these files are a great resource.

Get-Member

The final helpful cmdlet we’re going to look at in this chapter is Get-Member. Earlier in the chapter, we discussed how PowerShell produces objects rather than text output like some shells and scripting languages. Get-Member allows you to see the members of those objects, their properties, and the methods that may be used on them. It’s easier to show rather than tell, so go ahead and type the following into your shell:

Get-Process | Get-Member

Note

The vertical line between the two cmdlets is called the pipeline character, |. It’s not a lower case L – on my en-GB standard PC keyboard, it’s on the lower left, next to the Z key, and on a standard en-US keyboard, it’s between the Enter and Backspace keys. If your keyboard doesn’t have a solid vertical bar (|), then the broken vertical bar (¦) will work.

What you’re doing here is piping the output of the Get-Process cmdlet into the next cmdlet as input, which in this case is Get-Member. We’ll be doing plenty of work on the pipeline in later chapters. Get-Member will tell you the type of object you’ve given it, in this case a System.Diagnostics.Process object, and the methods, properties, alias properties, and events associated with that object, like this:

Figure 1.16 – Some of the members of System.Diagnostics.Process

Figure 1.16 – Some of the members of System.Diagnostics.Process

A few pages earlier, in Figure 1.14, we looked at the properties of the pwsh processes running on your machine. These are the properties that were listed: NPM(K), PM(M), WS(M), CPU(s), ID, SI, and ProcessName. As you can now see, that’s Non-Paged Memory (K), Paged Memory (M), Working Set (M), and Session ID, which are all aliases, so that they can fit nicely into a table on the screen. The CPU(s) alias is derived in a slightly different way – it’s not set on the object. The ID and the process name are not aliases. M and K are abbreviations for Megabytes and Kilobytes, respectively. That’s a really small subset of all the properties available on the object. As you can see, there are also methods available that can be used to perform operations on the object.

Activity 2

Have a look at the methods. What method might you use to forcibly and immediately stop a process? If you get stuck, have a look at the methods here: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.

We’ll be returning to Get-Member more than once in the rest of the book, as it’s such a useful cmdlet.

Summary

We’ve done a lot in this chapter. We’ve discussed what PowerShell is and what it’s suited for, such as producing short pieces of automation code quickly and easily. We’ve downloaded and installed it in a few different ways, specifically by installing it from an .msi file and extracting it from a .zip file.

We’ve tried some different ways of starting it using the built-in shell, and finally, we’ve looked at three useful cmdlets: Get-Command, for finding cmdlets that we might use, Get-Help, for understanding how to use them, and Get-Member, to understand what output those cmdlets produce.

In the next chapter, we will explore how cmdlets work, explore parameters and syntax, and look at a useful application for working interactively with PowerShell: Windows Terminal.

Exercises

  1. What cmdlet would you use to generate a random number?
  2. How would you generate a random number between 1 and 10?
  3. What cmdlet would you use to list the contents of a folder?
  4. How would you also get the contents of the subfolders?
  5. What cmdlet would you use to create a new folder?
  6. What cmdlet will tell you how long your computer has been switched on?
  7. What cmdlet might redirect output to a file?
  8. What could you use the Get-Credential cmdlet for?
  9. How might you use the ConvertTo-HTML cmdlet?

Further reading

Left arrow icon Right arrow icon

Key benefits

  • Master the art of coding with Microsoft’s free, open-source cross-platform language
  • Understand essential programming concepts such as loops and objects through practical examples
  • Practice using PowerShell 7 with websites, APIs, and physical computing devices like Raspberry Pi
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Discover the capabilities of PowerShell 7 for your everyday tasks with this carefully paced tutorial that will help you master this versatile programming language. The first set of chapters will show you where to find and how to install the latest version of PowerShell, providing insights into the distinctive features that set PowerShell apart from other languages. You’ll then learn essential programming concepts such as variables and control flow, progressing to their applications. As you advance, you’ll work with files and APIs, writing scripts, functions, and modules. You’ll also gain proficiency in securing your PowerShell environment before venturing into different operating systems. Enriched with detailed practical examples tailored for Windows, Linux, macOS, and Raspberry Pi, each chapter weaves real-world scenarios to ignite your imagination and cement the principles you learn. You’ll be able to reinforce your understanding through self-assessment questions and delve deeper into the principles using comprehensive reading lists. By the end of this book, you’ll have the confidence to use PowerShell for physical computing and writing scripts for Windows administration.

What you will learn

Grasp the distinctive object-oriented nature of PowerShell 7 Explore the practical applications of standard programming concepts, such as control flow Find out how to interact with websites and APIs Implement best practices to secure your PowerShell environment and write secure code Get to grips with writing scripts, functions, and modules Develop the skills to troubleshoot your code Deploy PowerShell on various operating systems

Product Details

Country selected

Publication date : Feb 29, 2024
Length 468 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781801812986
Vendor :
Microsoft

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Feb 29, 2024
Length 468 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781801812986
Vendor :
Microsoft

Table of Contents

23 Chapters
Preface Chevron down icon Chevron up icon
1. Part 1: PowerShell Fundamentals Chevron down icon Chevron up icon
2. Chapter 1: Introduction to PowerShell 7 – What It Is and How to Get It Chevron down icon Chevron up icon
3. Chapter 2: Exploring PowerShell Cmdlets and Syntax Chevron down icon Chevron up icon
4. Chapter 3: The PowerShell Pipeline – How to String Cmdlets Together Chevron down icon Chevron up icon
5. Chapter 4: PowerShell Variables and Data Structures Chevron down icon Chevron up icon
6. Chapter 5: PowerShell Control Flow – Conditionals and Loops Chevron down icon Chevron up icon
7. Chapter 6: PowerShell and Files – Reading, Writing, and Manipulating Data Chevron down icon Chevron up icon
8. Chapter 7: PowerShell and the Web – HTTP, REST, and JSON Chevron down icon Chevron up icon
9. Part 2: Scripting and Toolmaking Chevron down icon Chevron up icon
10. Chapter 8: Writing Our First Script – Turning Simple Cmdlets into Reusable Code Chevron down icon Chevron up icon
11. Chapter 9: Don’t Repeat Yourself – Functions and Scriptblocks Chevron down icon Chevron up icon
12. Chapter 10: Error Handling – Oh No! It’s Gone Wrong! Chevron down icon Chevron up icon
13. Chapter 11: Creating Our First Module Chevron down icon Chevron up icon
14. Chapter 12: Securing PowerShell Chevron down icon Chevron up icon
15. Part 3: Using PowerShell Chevron down icon Chevron up icon
16. Chapter 13: Working with PowerShell 7 and Windows Chevron down icon Chevron up icon
17. Chapter 14: PowerShell 7 for Linux and macOS Chevron down icon Chevron up icon
18. Chapter 15: PowerShell 7 and the Raspberry Pi Chevron down icon Chevron up icon
19. Chapter 16: Working with PowerShell and .NET Chevron down icon Chevron up icon
20. Answers to Activities and Exercises Chevron down icon Chevron up icon
21. Index Chevron down icon Chevron up icon
22. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.