Home Cloud & Networking Mastering PowerShell Scripting - Fourth Edition

Mastering PowerShell Scripting - Fourth Edition

By Chris Dent
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Modules and Snap-Ins
About this book
PowerShell scripts offer a convenient way to automate various tasks, but working with them can be daunting. Mastering PowerShell Scripting takes away the fear and helps you navigate through PowerShell's capabilities.This extensively revised edition includes new chapters on debugging and troubleshooting and creating GUIs (online chapter). Learn the new features of PowerShell 7.1 by working with parameters, objects, and .NET classes from within PowerShell 7.1. This comprehensive guide starts with the basics before moving on to advanced topics, including asynchronous processing, desired state configuration, using more complex scripts and filters, debugging issues, and error-handling techniques. Explore how to efficiently manage substantial amounts of data and interact with other services using PowerShell 7.1. This book will help you to make the most of PowerShell's automation features, using different methods to parse data, manipulate regular expressions, and work with Windows Management Instrumentation (WMI).
Publication date:
June 2021
Publisher
Packt
Pages
788
ISBN
9781800206540

 

Introduction to PowerShell

PowerShell is a shell scripting language from Microsoft originally released for Windows in 2006. PowerShell was written to appeal to systems administrators and presents a great deal of its functionality as commands such as Get-ChildItem, Get-Content, New-Item, and so on. Microsoft Exchange was one of the first systems to embrace PowerShell with the release of Exchange 2007.

Windows PowerShell includes the original version through to 5.1, which is the final release of the Windows-specific shell. Windows PowerShell versions are based on .NET Framework.

In 2018, the first version of PowerShell Core was released with PowerShell 6. The move from .NET Framework to .NET Core allows the current versions of PowerShell to run on Linux and macOS, as well as Windows.

The use of .NET Core 2 in PowerShell 6 introduced a challenge for PowerShell users as it did not include everything that was in.NET Framework. For example, it was not possible to use scripts...

 

What is PowerShell?

PowerShell is a mixture of a command-line interface, a functional programming language, and an object-oriented programming language. PowerShell is based on Microsoft .NET, which gives it a level of open flexibility that was not available in Microsoft's scripting languages (such as VBScript or batch) before this.

PowerShell has been written to be highly discoverable. It has substantial built-in help that's accessible within the console via the Get-Help command. PowerShell has commands such as Get-Member to allow a user to discover the details of the values it returns.

PowerShell 7 can be installed alongside Windows PowerShell. Windows PowerShell is installed in Windows\System32 by the Windows Management Framework packages, and it cannot be moved elsewhere. PowerShell Core and 7 are both installed in the Program Files folder and do not share any of the files used by Windows PowerShell. Preview versions of PowerShell can be installed...

 

PowerShell editors

While you can develop PowerShell scripts using the Notepad application alone, it is rarely desirable. Using an editor that was designed to work with PowerShell can save a lot of time.

Specialized PowerShell editors such as Visual Studio Code (VS Code) and PowerShell Studio offer automatic completion (IntelliSense). IntelliSense reduces the amount of cross-referencing help content required while writing code. Finding a comfortable editor early on is a good way to ease into PowerShell; memorizing commands and parameters is not necessary.

In addition to the aforementioned editors, Windows PowerShell comes with PowerShell ISE. PowerShell ISE has not been updated for PowerShell 6 and higher and will only function correctly for Windows PowerShell.

PowerShell Studio is not free but includes graphical user interface development features.

VS Code is a highly recommended editor for PowerShell as it is free. VS Code is an open-source editor that was published...

 

Getting help

PowerShell includes a built-in help system accessible using the Get-Help command. Gaining confidence using the built-in help system is an important part of working with PowerShell. Script authors and PowerShell developers can easily write their own help content when working with functions, scripts, and script modules.

Updatable help

The concept of updatable help was added in Windows PowerShell 3. It allows users to obtain the most recent versions of their help documentation outside of PowerShell on a web service. Help content can be downloaded and installed using the Update-Help command in PowerShell.

Which modules support updatable help?

You can view a list of modules that support updatable help by running the following command:

Get-Module -ListAvailable | Where-Object HelpInfoURI 

Help for the core components of PowerShell is not part of the PowerShell 7 installation package. Content must be downloaded before it can be viewed...

 

Command naming and discovery

Commands in PowerShell are formed around verb and noun pairs in the form verb-noun.

This feature is useful when finding commands; it allows you to make educated guesses so that there is little need to memorize long lists of commands.

Verbs

The list of verbs is maintained by Microsoft. Verbs are words such as Add, Get, Set, and New. This formal approach to naming commands greatly assists in discovery.

You can view the verbs available in PowerShell using the following command:

Get-Verb 

Verbs are grouped around different areas, such as data, life cycle, and security. Complementary actions such as encryption and decryption tend to use verbs in the same group; for example, the verb Protect may be used to encrypt something and the verb Unprotect may be used to decrypt something.

Verb descriptions

A detailed list of verbs, along with their use cases, is available on MSDN:

https://docs.microsoft.com/en-us/powershell...

 

Parameters, values, and parameter sets

As seen while looking at syntax in Get-Help, commands accept a mixture of parameters. The following sections show how these parameters are described in help and how to use them.

Parameters

When viewing help for a command, several different conventions are used to describe when a parameter is required and how it should be used. These conventions include:

  • Optional parameters, where parameter names and arguments are enclosed in a single pair of square brackets.
  • Optional positional parameters, the same as an optional parameter but with the parameter name also enclosed in square brackets.
  • Mandatory parameters, where the parameter name and argument are not bracketed.
  • Mandatory positional parameters, where the parameter name is in square brackets, but the argument is not.

The following sections show each of these conventions in greater detail.

Optional parameters

Optional parameters are surrounded...

 

Introduction to providers

A provider in PowerShell is a specialized interface to a service or dataset that presents items to the end user in the same style as a filesystem.

All operating systems include the following providers:

  • Alias: PowerShell aliases
  • Environment: Environment variables (for the process)
  • FileSystem: Files and folders
  • Function: Any functions in the session
  • Variable: Any variables in the session

Windows operating systems also include Windows-specific providers:

  • Registry: All loaded registry hives
  • Certificate: The LocalMachine and CurrentUser certificate stores
  • WSMan: Windows remoting configuration

A number of modules, such as the ActiveDirectory and WebAdministration modules, add service-specific providers when imported.

A longer description of Providers can be seen by viewing the about file:

Get-Help about_Providers

You can view the providers available in the current PowerShell...

 

Introduction to splatting

Splatting is a way of defining the parameters of a command before calling it. This is an important and often underrated technique that the PowerShell team added in PowerShell 2.

Splatting is often used to solve three potential problems in a script:

  • Long lines caused by commands that need many parameters
  • Conditional use of parameters
  • Repetition of parameters across several commands

Individual parameters are written in a hashtable (@{}), and then the @ symbol is used to tell PowerShell that the content of the hashtable should be read as parameters.

This example supplies the Name parameter for the Get-Process command, and is normally written as Get-Process -Name explorer:

$getProcess = @{
    Name = 'explorer'
}
Get-Process @getProcess

In this example, getProcess is used as the name of the variable for the hashtable. The name is arbitrary; any variable name can be used.

Splatting can be used...

 

Parser modes

The parser in PowerShell is responsible for taking what is typed into the console, or what is written in a script, and turning it into something PowerShell can execute. The parser has two different modes that explain, for instance, why strings assigned to variables must be quoted, but strings as arguments for parameters only need quoting if the string contains a space.

The parser modes are different modes:

  • Argument mode
  • Expression mode

Mode switching allows PowerShell to correctly interpret arguments without needing values to be quoted. In the following example, the argument for the Name parameter only needs quoting if the name contains spaces:

Get-Process -Name pwsh

The parser is running in Argument mode at the point the pwsh value is used and therefore literal text is treated as a value, not something to be executed.

This means that, in the following example, the second command is interpreted as a string and not executed...

 

Experimental features

PowerShell 7 uses experimental features to make some new functionality available, which is not yet considered to be a mainstream feature. Three commands are available for working with experimental features:

  • Enable-ExperimentalFeature
  • Disable-ExperimentalFeature
  • Get-ExperimentalFeature

Get-ExperimentalFeature can be used to view the available features. The list of features changes, depending on the version of PowerShell. The following list has been taken from PowerShell 7.0.2.

PS> Get-ExperimentalFeature
Name                                Enabled Source
----                                ------- ------
PSCommandNotFoundSuggestion           False PSEngine
PSImplicitRemotingBatching            False PSEngine
PSNullConditionalOperators            False PSEngine
Microsoft.PowerShell.Utility.PSMan…   False C:\program files\powersh…
PSDesiredStateConfiguration.Invoke…   False C:\program files\powersh...
 

Summary

This chapter contained several foundational topics for PowerShell, starting with picking an editor, using help content, and command discovery.

The ability to use the help system and discover commands is vital, regardless of skill level. The availability of help content in the shell allows new commands to be quickly incorporated and used.

Naming plays an important role in PowerShell. Strict use of a reasonably small set of verbs greatly enhances discovery and, reasonable assumptions can be made about a command before reaching for help content. PowerShell tends to use longer and descriptive command names compared with other scripting languages.

Once a command has been found, it is important to understand how to use the help content and the parameters a command offers to use it effectively.

Providers allow access to data in a similar manner to using a filesystem. Providers play and important role in PowerShell and are explored again later in this book when...

About the Author
  • Chris Dent

    Chris Dent is an automation specialist with deep expertise in the PowerShell language. Chris is often found answering questions about PowerShell in both the UK and virtual PowerShell user groups. Chris has been developing in PowerShell since 2007 and has released several modules over the years.

    Browse publications by this author
Latest Reviews (2 reviews total)
Pubblicazioni interessanti scritti con il giusto livello tecnico ma soprattutto in modo chiaro.
One of the best and most comprehensive books on PowerShell.
Mastering PowerShell Scripting - Fourth Edition
Unlock this book and the full library FREE for 7 days
Start now