Discover millions of audiobooks, ebooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Mastering PowerShell Scripting: Automate repetitive tasks and simplify complex administrative tasks using PowerShell
Mastering PowerShell Scripting: Automate repetitive tasks and simplify complex administrative tasks using PowerShell
Mastering PowerShell Scripting: Automate repetitive tasks and simplify complex administrative tasks using PowerShell
Ebook2,727 pages10 hours

Mastering PowerShell Scripting: Automate repetitive tasks and simplify complex administrative tasks using PowerShell

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
Release dateMay 24, 2024
ISBN9781805124153
Mastering PowerShell Scripting: Automate repetitive tasks and simplify complex administrative tasks using PowerShell

Related to Mastering PowerShell Scripting

Related ebooks

System Administration For You

View More

Reviews for Mastering PowerShell Scripting

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Mastering PowerShell Scripting - Chris Dent

    9781805120278.png

    Mastering PowerShell Scripting

    Fifth Edition

    Automate repetitive tasks and simplify complex administrative tasks using PowerShell

    Chris Dent

    Mastering PowerShell Scripting

    Fifth Edition

    Copyright © 2024 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Senior Publishing Product Manager: Reshma Raman

    Acquisition Editor – Peer Reviews: Tejas Mhasvekar

    Project Editor: Amisha Vathare

    Content Development Editor: Deepayan Bhattacharjee

    Copy Editor: Safis Editing

    Technical Editor: Kushal Sharma

    Proofreader: Safis Editing

    Indexer: Tejal Daruwale Soni

    Presentation Designer: Ganesh Bhadwalkar

    Developer Relations Marketing Executive: Meghal Patel

    First published: April 2015

    Second edition: October 2017

    Third edition: February 2019

    Fourth edition: June 2021

    Fifth edition: May 2024

    Production reference: 1160524

    Published by Packt Publishing Ltd.

    Grosvenor House

    11 St Paul’s Square

    Birmingham

    B3 1RB, UK.

    ISBN 978-1-80512-027-8

    www.packt.com

    Contributors

    About the author

    Chris Dent is an automation specialist with a deep interest in the PowerShell language. Chris has been learning and using PowerShell since 2007 and is often found answering questions in the Virtual PowerShell User Group.

    I would like to thank my wife, Emily, and my children, Lizzy and Thomas, for their continued support.

    About the reviewer

    Mike Roberts is a PowerShell ninja, both in his profession as well as his blog, where he teaches it: https://gngr.ninja. Through his blog, he hopes to educate and inspire others by demonstrating what different technologies are capable of.

    I am eternally grateful for the support of my friends and family. Thank you!

    Learn more on Discord

    Read this book alongside other users, PowerShell experts, and the author himself. Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more.

    Scan the QR code or visit the link to join the community.

    https://packt.link/SecNet

    Contents

    Preface

    Who this book is for

    What this book covers

    To get the most out of this book

    Get in touch

    Introduction to PowerShell

    Technical requirements

    What is PowerShell?

    The command line

    PowerShell editors

    Getting help

    Updatable help

    The Get-Help command

    Syntax

    Examples

    Parameter

    Detailed and Full switches

    Save-Help

    Update-Help

    About_* help files

    Command naming and discovery

    Verbs

    Nouns

    Finding commands

    Aliases

    About profile scripts

    Parameters, values, and parameter sets

    Parameters

    Optional parameters

    Optional positional parameters

    Mandatory parameters

    Mandatory positional parameters

    Switch parameters

    Parameter values

    Parameter sets

    Common parameters

    Confirm and WhatIf

    Confirm and ConfirmPreference

    WhatIf and WhatIfPreference

    Force parameter

    PassThru parameter

    Introduction to providers

    Drives and providers

    Introduction to splatting

    Splatting to avoid long lines

    Conditional use of parameters

    Splatting to avoid repetition

    Splatting and positional parameters

    Parser modes

    Experimental features

    Summary

    Modules

    Introducing modules

    The Get-Module command

    The Import-Module command

    The Remove-Module command

    PSModulePath in PowerShell

    Module content

    Using Windows PowerShell modules in PowerShell 7

    Finding and installing modules

    What is the PowerShell Gallery?

    The Find-Module command

    The Install-Module command

    The Update-Module command

    The Save-Module command

    Microsoft.PowerShell.PSResourceGet

    Repositories

    Version ranges

    PowerShell repositories

    Creating an SMB repository

    NuGet repositories

    About snap-ins

    Summary

    Variables, Arrays, and Hashtables

    Naming and creating variables

    Provider variables

    Variables in strings

    Variable types

    Assignment with types on the right

    Assignment with types on the left

    Value and reference types

    Type conversion

    Variable commands

    Get-Variable

    New-Variable

    Set-Variable

    Remove-Variable

    Clear-Variable

    Variable provider

    Variable scope

    Accessing variables

    Scope modifiers

    Numeric scopes

    Private variables

    About arrays

    Array type

    Creation by assignment

    Creating an array

    Arrays with a type

    Adding elements to an array

    List and ArrayList

    Selecting elements from an array

    Changing element values in an array

    Removing elements

    Removing elements by index

    Filling variables from arrays

    Multi-dimensional and jagged arrays

    About hashtables

    Creating a Hashtable

    Adding, changing, and removing keys

    Using a hashtable to filter

    Enumerating a Hashtable

    About Ordered

    Summary

    Working with Objects in PowerShell

    Pipelines

    Standard output

    Non-standard output

    The Object pipeline

    Members

    The Get-Member command

    Accessing object properties

    Access modifiers

    Using methods

    Return types and argument types

    Creating and modifying objects

    Using PSCustomObject

    The New-Object command

    The Add-Member command

    Add-Member and custom objects

    Enumerating and filtering

    The ForEach-Object command

    Begin and End parameters

    The Parallel parameter

    The MemberName parameter

    The Where-Object command

    Selecting and sorting

    The Select-Object command

    Calculated properties

    The ExpandProperty parameter

    The Unique parameter

    Property sets

    The Sort-Object command

    The Unique parameter

    Grouping and measuring

    The Group-Object command

    The Measure-Object command

    Comparing

    Importing, exporting, and converting

    The Export-Csv command

    The Import-Csv command

    Export-Clixml and Import-Clixml

    The Tee-Object command

    Formatting

    Formatting and exporting

    The Format-Table command

    The Format-List command

    Select-Object, Write-Host, and inline output

    Format-only properties

    Summary

    Operators

    Precedence, grouping, and sub-expressions

    Operator precedence

    Grouping

    Sub-expression operator

    Array sub-expression operator

    Unary, binary, and ternary operators

    About the ternary operator

    Arithmetic operators

    Addition operator

    Subtraction operator

    Multiplication operator

    Division operator

    Remainder operator

    Increment and decrement operators

    Comparison operators

    eq and ne

    like and notlike

    Greater than and less than

    Case sensitivity

    Comparison operators and arrays

    Comparisons to null

    contains and in

    Regular expression-based operators

    match and notmatch

    replace

    split

    Logical operators

    and

    or

    not

    xor (eXclusive OR)

    Bitwise operators

    band (bitwise AND)

    bor (bitwise OR)

    bxor (bitwise eXclusive OR)

    bnot (bitwise NOT)

    shl and shr (shift left and right operators)

    Assignment operators

    Assign, add and assign, and subtract and assign

    Multiply and assign, divide and assign, and modulus and assign

    Statements can be assigned to a variable

    Assignment and other operators

    Type operators

    as

    is and isnot

    Redirection operators

    About Write-Host

    Redirection to a file

    PowerShell and default file encoding

    Redirecting streams to standard output

    Only stdout

    Redirection to null

    Other operators

    Comma

    Index

    Range

    Call

    Format

    join

    Null coalescing

    Null coalescing assignment

    Null conditional

    Pipeline chain

    Background

    Summary

    Conditional Statements and Loops

    if, else, and elseif

    Assignment within if statements

    Implicit Boolean

    switch statements

    switch statements and arrays

    switch statements and files

    Wildcard and Regex parameters

    Script block cases

    switch statements and enums

    switch, break, and continue

    Loops

    foreach loop

    foreach keyword and foreach alias

    for loop

    do-until and do-while loops

    while loop

    Loops, break, and continue

    break and continue outside loops

    Loops and labels

    Loops, queues, and stacks

    Summary

    Working with .NET

    Assemblies

    About the GAC

    Types

    Type descriptions are objects in PowerShell

    Enumerations

    Classes

    Namespaces

    The using keyword

    Using namespaces

    Using assemblies

    Type accelerators

    About PSCustomObject and Ordered

    Members

    Constructors

    Properties

    Methods

    Fluent interfaces

    Static methods

    About the new() method

    Static properties

    Reflection in PowerShell

    The TypeAccelerators type

    The ArgumentTypeConverterAttribute type

    About generics

    Generic classes

    Generic methods

    Summary

    Online Chapter

    Files, Folders, and the Registry

    Working with providers

    Navigating

    Getting items

    Drives

    Items

    Paths and .NET

    Testing for existing items

    Testing filesystem paths

    Testing registry paths

    Testing path type

    Creating items

    Reading and writing content

    Reading and writing in a pipeline

    Reading all content

    Writing content

    About text file encoding

    Temporary files

    Removing items

    Invoking items

    Item properties

    Properties and the filesystem

    Adding and removing file attributes

    Registry values

    Registry values and environment variables

    Searching for items

    Windows permissions

    Access and audit

    Rule protection

    Inheritance and propagation flags

    Removing ACEs

    Copying lists and entries

    Adding ACEs

    Filesystem rights

    Registry rights

    Numeric values in the ACL

    Ownership

    Transactions

    File catalog commands

    About hashing

    New-FileCatalog

    Test-FileCatalog

    Summary

    Windows Management Instrumentation

    Working with WMI

    WMI classes

    WMI commands

    CIM commands

    Getting instances

    Getting classes

    Calling methods

    Creating instances

    Removing instances

    Working with CIM sessions

    Associated classes

    The WMI Query Language

    Understanding SELECT, WHERE, and FROM

    Escape sequences and wildcards

    Comparison operators

    WQL filters and dates

    Logic operators

    Quoting values

    Associated classes

    WMI object paths

    Using ASSOCIATORS OF

    WMI type accelerators

    Getting instances

    Working with dates

    Getting classes

    Calling methods

    Creating instances

    Associated classes

    Permissions

    Sharing permissions

    Creating a shared directory

    Getting a security descriptor

    Adding an access control entry

    Setting the security descriptor

    WMI permissions

    Getting a security descriptor

    The access mask

    WMI and SDDL

    Summary

    Working with HTML, XML, and JSON

    ConvertTo-Html

    Multiple tables

    Adding style

    ConvertTo-Html and Send-MailMessage

    Windows PowerShell and ConvertTo-Html

    Modifying HTML content

    XML commands

    About XML

    Elements and attributes

    Namespaces

    Schemas

    Select-Xml

    Select-Xml and namespaces

    ConvertTo-Xml

    System.Xml

    The XML type accelerator

    XPath and XmlDocument

    SelectNodes and XPathNodeList

    Working with namespaces

    Creating XML documents

    Modifying element and attribute values

    Adding elements

    Removing elements and attributes

    Copying nodes between documents

    Schema validation

    Inferring a schema

    System.Xml.Linq

    Opening documents

    Selecting nodes

    Creating documents

    Working with namespaces

    Modifying element and attribute values

    Adding nodes

    Removing nodes

    Schema validation

    JSON

    ConvertTo-Json

    EnumsAsStrings

    AsArray

    EscapeHandling

    ConvertFrom-Json

    AsHashtable

    NoEnumerate

    Test-Json

    Summary

    Web Requests and Web Services

    Technical requirements

    Web requests

    HTTP methods

    Using Invoke-WebRequest

    About parsing web pages

    Downloading files

    Using the HEAD method

    HTTPS

    Security protocols

    Certificate validation

    Windows PowerShell and certificate validation

    Capturing SSL errors

    Working with REST

    Simple requests

    Using basic authentication

    Requests with arguments

    Working with paging

    OAuth

    Creating an application

    Getting an authorization code

    Implementing an HTTP listener

    Requesting an access token

    Using a token

    Working with SOAP

    Finding a SOAP service

    SOAP in Windows PowerShell

    New-WebServiceProxy

    Methods

    Methods and enumerations

    Methods and SOAP objects

    Overlapping services

    SOAP in PowerShell 7

    Getting the WSDL document

    Discovering methods and enumerations

    Running methods

    Summary

    Remoting and Remote Management

    Technical requirements

    Executing remote commands

    Enter-PSSession

    Invoke-Command

    Parallel execution

    Catching remoting failures

    Local functions and remote sessions

    Using ArgumentList

    The using scope modifier

    PS Sessions

    New-PSSession and Get-PSSession

    Disconnected sessions

    Import-PSSession

    Export-PSSession

    Copying items between sessions

    WS-Management

    Enabling and configuring remoting

    The WSMan drive

    Remoting and SSL

    User Account Control

    Trusted hosts

    Remoting on Linux

    Remoting over SSH

    Connecting from Windows to Linux

    Connecting from Linux to Windows

    The double-hop problem

    CredSSP

    Passing credentials

    CIM sessions

    Get-CimSession

    Using CIM sessions

    Just Enough Administration

    Session configuration

    Role capabilities

    Summary

    Asynchronous Processing

    Working with jobs

    Start-Job, Get-Job, and Remove-Job

    Receive-Job

    Wait-Job

    Jobs and the using scope modifier

    The background operator

    The ThreadJob module

    Batching jobs

    Reacting to events

    The Register-ObjectEvent and *-Event commands

    Action, Event, EventArgs, and MessageData parameters

    Get-EventSubscriber and Unregister-Event

    Using runspaces and runspace pools

    Creating a PowerShell instance

    The Invoke and BeginInvoke methods

    About Streams and InvocationStateInfo

    Running multiple instances

    Using the RunspacePool object

    About the InitialSessionState object

    Adding modules and snap-ins

    Adding variables

    Adding functions

    Using the InitialSessionState and RunspacePool objects

    Using thread-safe objects

    Managing concurrent access

    Summary

    Graphical User Interfaces

    About Windows Presentation Foundation (WPF)

    Designing a UI

    About XAML

    Displaying the UI

    Layout

    Using the Grid control

    Using the StackPanel control

    Using the DockPanel control

    About Margin and Padding

    Naming and locating controls

    Handling events

    Buttons and the Click event

    ComboBox and SelectionChanged

    Adding elements programmatically

    Sorting a ListView

    Responsive interfaces

    Import-Xaml and runspace support

    Errors in the background

    Using the Dispatcher

    ScriptBlock runspace affinity

    Using the Action delegate

    Using the Func delegate

    Summary

    Scripts, Functions, and Script Blocks

    About style

    Capabilities of scripts, functions, and script blocks

    Scripts and using statements

    Scripts and the Requires statement

    Nesting functions

    Script blocks and closures

    Parameters and the param block

    Parameter types

    Default values

    Cross-referencing parameters

    The CmdletBinding attribute

    Common parameters

    CmdletBinding properties

    ShouldProcess and ShouldContinue

    ShouldProcess

    ShouldContinue

    The Alias attribute

    begin, process, end, and clean

    begin

    process

    end

    clean

    Named blocks and return

    Managing output

    The Out-Null command

    Assigning to null

    Redirecting to null

    Casting to void

    Working with long lines

    Line break after a pipe

    Line break after an operator

    Using the array sub-expression operator to break up lines

    Comment-based help

    Output help

    Parameter help

    Examples

    Summary

    Parameters, Validation, and Dynamic Parameters

    The Parameter attribute

    Position and positional binding

    The DontShow property

    The ValueFromRemainingArguments property

    The HelpMessage property

    Validating input

    The PSTypeName attribute

    Validation attributes

    The ValidateNotNull attribute

    The ValidateNotNullOrEmpty attribute

    The ValidateNotNullOrWhitespace attribute

    The ValidateCount attribute

    The ValidateLength attribute

    The ValidatePattern attribute

    The ValidateRange attribute

    The ValidateScript attribute

    The ValidateSet attribute

    The ValidateDrive attribute

    The ValidateUserDrive attribute

    The Allow attributes

    The AllowNull attribute

    The AllowEmptyString attribute

    The AllowEmptyCollection attribute

    PSReference parameters

    Pipeline input

    About ValueFromPipeline

    Accepting null input

    Input object types

    Using ValueFromPipeline for multiple parameters

    About ValueFromPipelineByPropertyName

    ValueFromPipelineByPropertyName and parameter aliases

    Defining parameter sets

    Argument completers

    The ArgumentCompleter attribute

    Using Register-ArgumentCompleter

    About CompletionResult

    Non-literal values

    Listing registered argument completers

    Dynamic parameters

    Creating a RuntimeDefinedParameter object

    Using RuntimeDefinedParameterDictionary

    Using dynamic parameters

    PSBoundParameters

    RuntimeDefinedParameterDictionary

    Conditional parameters

    Summary

    Classes and Enumerations

    Defining an enumeration

    Enum and underlying types

    Automatic value assignment

    Enum or ValidateSet

    The Flags attribute

    Using enumerations to convert a value

    Creating a class

    Properties

    Constructors

    Methods

    The Hidden modifier

    The static modifier

    Inheritance

    Constructors and inheritance

    Calling methods in a parent class

    Working with interfaces

    Implementing IComparable

    Implementing IEquatable

    Supporting casting

    Classes and runspace affinity

    Transformation, validation, and completion

    Argument transformation attribute classes

    Validation attribute classes

    ValidateArgumentsAttribute

    ValidateEnumeratedArgumentsAttribute

    ValidateSet value generator

    Argument completers

    IArgumentCompleter

    IArgumentCompleterFactory

    Classes and Microsoft Desired State Configuration

    Implementing Get

    Implementing Set

    Implementing Test

    Using the resource

    Summary

    Online Chapter

    Testing

    Technical requirements

    Static analysis

    PSScriptAnalyzer

    Configurable rules

    Suppressing rules

    Using AST

    Visualizing the AST

    Searching the AST

    Tokenizer

    Custom script analyzer rules

    Creating a custom rule

    AST-based rules

    Token-based rules

    Testing with Pester

    Testing methodologies

    What to test

    Describing tests

    About the Describe and Context keywords

    About the It keyword

    Should and assertions

    Testing for errors

    Iteration with Pester

    Using the ForEach parameter

    ForEach with Describe and Context

    Conditional testing

    Using Set-ItResult

    Using Skip

    Pester phases

    Before and After blocks

    Mocking commands

    Parameter variables

    Parameter filtering

    Overriding mocks

    Mocking non-local commands

    Mocking objects

    Adding methods to PSCustomObject

    Disarming .NET types

    Mocking CIM objects

    InModuleScope

    Pester in scripts

    Summary

    Error Handling

    Error types

    Terminating errors

    Non-terminating errors

    Error actions

    About Get-Error

    Raising errors

    Error records

    Raising non-terminating errors

    Using the WriteError method

    Raising terminating errors

    Using the ThrowTerminatingError method

    Catching errors

    ErrorVariable

    try, catch, and finally

    Rethrowing errors

    Inconsistent error handling

    throw and ErrorAction

    Terminating errors in child scopes

    Nesting try, catch, and finally

    About trap

    Using trap

    trap, scope, and continue

    Summary

    Debugging

    Common problems

    Dash characters

    Operator usage

    Assignment instead of equality

    -or instead of -and

    Negated array comparisons

    Use of named blocks

    Code outside of a named block

    Pipeline without process

    Problems with variables

    About strict mode

    Variables and types

    Types and reserved variables

    Debugging in the console

    Setting a command breakpoint

    Using variable breakpoints

    Setting a line breakpoint

    Debugging in Visual Studio Code

    Using the debugger

    Viewing CALL STACK

    Using launch configurations

    Debugging modules

    Using WATCH

    Debugging other PowerShell processes

    Summary

    Other Books You May Enjoy

    Index

    Landmarks

    Cover

    Index

    Preface

    PowerShell is an object-oriented scripting language aimed at systems administrators that was invented by Jeffrey Snover. PowerShell was first conceived as far back as 2002 and entered mainstream use in 2006. Exchange 2007 was one of the first major systems to adopt it as an administration language.

    PowerShell has come a long way over the years. PowerShell 7 smooths over a lot of the rough edges in the original releases of the cross-platform PowerShell Core (PowerShell 6).

    Like any good scripting language, PowerShell is the glue that ties automated processes together. It is a vital part of the Microsoft ecosystem and is great in heterogeneous environments.

    Who this book is for

    This book is for PowerShell developers, system administrators, and script authors, new and old, who wish to explore the capabilities and possibilities of the language.

    What this book covers

    PowerShell fundamentals are explored in the first five chapters:

    Chapter 1, Introduction to PowerShell, introduces you to editors, the help system, command naming, and more.

    Chapter 2, Modules, explores finding, installing, and using modules in PowerShell. Snap-ins are not part of PowerShell 7 but are briefly explored as a legacy feature of PowerShell 5.

    Chapter 3, Variables, Arrays, and Hashtables, covers an important topic in PowerShell. The chapter explores the use of variables, as well as the capabilities of collections.

    Chapter 4, Working with Objects in PowerShell, looks at the concept of objects in PowerShell and the generic commands available for selecting, filtering, and manipulating values.

    Chapter 5, Operators, explores the large variety of operators available in PowerShell.

    Then, we move on to working with data in PowerShell:

    Chapter 6, Conditional Statements and Loops, covers the tools used to make decisions in scripts in PowerShell. This chapter explores keywords like

    If

    , and the different loop styles available.

    Chapter 7, Working with .NET, dives into .NET, which was used to create the PowerShell language and is available within PowerShell.

    Chapter 8, Strings, Numbers, and Dates, covers a vital part of any scripting language, and PowerShell is no exception. This chapter explores the different techniques available for working with such values. This chapter can be accessed using https://static.packt-cdn.com/downloads/9781805120278_Chapter_8_and_9.pdf.

    Chapter 9, Regular Expressions, discusses regular expressions, which are an incredibly useful inclusion in PowerShell. You can use regular expressions to make short work of string parsing tasks. The chapter ends by walking through several practical parsing examples. This chapter can be accessed using https://static.packt-cdn.com/downloads/9781805120278_Chapter_8_and_9.pdf.

    Chapter 10, File, Folders, and the Registry, explores the use of providers in PowerShell, which are mostly used to access the file system and, in Windows, the registry.

    Chapter 11, Windows Management Instrumentation, explores WMI in PowerShell, a significant part of the Windows operating system since Windows NT.

    Chapter 12, Working with HTML, XML, and JSON, looks at the PowerShell commands and .NET types that you can use to work with these different text-based formats.

    Chapter 13, Web Requests and Web Services, explores basic web requests before diving into using PowerShell to work with REST APIs, using the API for GitHub as an example. Support for SOAP in PowerShell 7 is less complete than in PowerShell 5.1. SOAP is explored by way of a web service project via Visual Studio.

    Chapters 14 to 16 explores automating with PowerShell:

    Chapter 14, Remoting and Remote Management, examines the configuration and use of PowerShell Remoting in both Windows and Linux.

    Chapter 15, Asynchronous Processing, dives into the realm of background jobs in PowerShell before exploring .NET events in PowerShell. The chapter ends with a look at runspaces and runspace pools.

    Chapter 16, Graphical User Interfaces, shows you how to implement responsive user interfaces in PowerShell.

    For the rest of the book, we learn how to extend PowerShell by adding and implementing new functionalities:

    Chapter 17, Scripts, Functions, and Script Blocks, explores the building blocks of larger scripts and modules. The chapter looks at how to define parameters, work in a pipeline, and manage output.

    Chapter 18, Parameters, Validation, and Dynamic Parameters, looks at the many options available for defining parameters and validating input in PowerShell.

    Chapter 19, Classes and Enumerations, shows off the capabilities of the

    class

    and

    enum

    keywords, which were introduced with PowerShell 5. The chapter includes an exploration of class inheritance and implementing .NET interfaces. This chapter includes a brief look at writing class-based DSC resources.

    Chapter 20, Building Modules, explores the key concepts of creating a module in PowerShell using PowerShell code. The chapter shows off some of the common approaches available to module authors. This chapter can be accessed using https://static.packt-cdn.com/downloads/9781805120278_Chapter_20.pdf.

    Chapter 21, Testing, explores static analysis using

    PSScriptAnalyzer

    as well as acceptance and unit testing using the Pester framework.

    Chapter 22, Error Handling, looks at the complex topic of handling errors in PowerShell, including an exploration of both terminating and non-terminating errors.

    Chapter 23, Debugging, uses the built-in debugger in PowerShell and Visual Studio to delve into some of the common problems encountered when debugging scripts.

    To get the most out of this book

    Some familiarity with operating systems would be beneficial

    Visual Studio Code (https://code.visualstudio.com/) is used a few times in the book and is a useful tool to have available throughout

    Download the example code files

    The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Mastering-PowerShell-Scripting-5E/. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Download the color images

    We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781805120278.

    Conventions used

    There are a number of text conventions used throughout this book.

    CodeInText

    : Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: "By default,

    Save-Help

    (and

    Update-Help

    ) will not download help content more often than once every 24 hours."

    A block of code is set as follows:

    Get-Process

    |

    Select-Object

    Name, ID

    -First

    1

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    Get-Process

    |

    Select-Object

    Name

    , ID

    Any command-line input or output is written as follows:

    PS>

    Get-Process | Select-Object Name, ID -First 1 Name Id ---- -- Pwsh 5068

    Bold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: "Select System info from the Administration panel."

    Warnings or important notes appear like this.

    Tips and tricks appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: Email

    [email protected]

    and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at

    [email protected]

    .

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.

    Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at

    [email protected]

    with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

    Share your thoughts

    Once you’ve read Mastering PowerShell Scripting, Fifth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

    Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

    Download a free PDF copy of this book

    Thanks for purchasing this book!

    Do you like to read on the go but are unable to carry your print books everywhere?

    Is your eBook purchase not compatible with the device of your choice?

    Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

    Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

    The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.

    Follow these simple steps to get the benefits:

    Scan the QR code or visit the link below:

    https://packt.link/free-ebook/9781805120278

    Submit your proof of purchase.

    That’s it! We’ll send your free PDF and other benefits to your email directly.

    1

    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.

    Active Directory tools followed a few years later along with tools to manage on-premises virtualization platforms from VMware and Microsoft Hyper-V.

    More recently, PowerShell has been offered as a management tool for cloud platforms like Azure and AWS. In addition to modules that can be used to interact with either service, Azure and AWS both offer in-browser shells to directly manage services.

    Windows PowerShell, or the Desktop edition, 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 latest versions of PowerShell to run on Linux and macOS, as well as Windows.

    Since then, PowerShell 7 has been released and continues to receive new features and updates. The core edition of PowerShell has seen a move through .NET Core 3.1 to .NET 8 with PowerShell 7.4.

    The other significant difference between Windows PowerShell and PowerShell is that PowerShell 6 and above are open source. The project is on GitHub and is open to public contributors: https://github.com/powershell/powershell.

    A significant number of community contributors have been driving change, making commands more usable and useful, adding new features, and fixing bugs. For example,

    Invoke-WebRequest

    and

    Invoke-RestMethod

    were completely overhauled in PowerShell 6, greatly improving how they perform while retaining much in the way of backward compatibility.

    Several core commands were removed while these changes were being made. For example, the

    Get-WmiObject

    and

    New-WebServiceProxy

    commands have been removed. The reasons for this vary; in some cases, the commands are fundamentally incompatible with .NET Core. In a few cases, the commands were under restricted licensing agreements and could not be made open source. These differences are highlighted in this book and alternatives are demonstrated where possible.

    Despite all this change, PowerShell still maintains strong backward compatibility, with very few breaking changes between the two editions. Operators and language keywords remain the same, and most changes are new features instead of changes to existing ones. Exceptions to this tend to be edge cases like parameter changes to

    Get-Content

    when reading byte content. These differences in behavior are highlighted throughout this book. Lessons learned using Windows PowerShell can be applied to PowerShell 7, and they will continue to be applicable to future versions of PowerShell.

    This book is split into several sections. Much of this book is intended to act as a reference. The following topics will be covered:

    Exploring PowerShell fundamentals

    Working with data

    Automating with PowerShell

    Extending PowerShell

    While exploring the fundamentals of the language, this first section of the book attempts to cover as many of the building blocks as possible.

    This chapter explores a diverse set of topics:

    What is PowerShell?

    The command line

    PowerShell editors

    Getting help

    Command naming and discovery

    About profile scripts

    Parameters, values, and parameter sets

    Introduction to providers

    Introduction to splatting

    Parser modes

    Experimental features

    Technical requirements

    This chapter makes use of the following on the Windows platform: PowerShell 7.

    At the start of this chapter, PowerShell was described as a shell scripting language. But this is perhaps not a complete description.

    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, which is 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 any objects 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 alongside the full releases and have separate folder structures.

    Command line customization is a popular subject, and several tools are available to help.

    The command line

    PowerShell 7 comes with a module called PSReadLine. A module is a collection of related commands. Modules are explored in greater detail in Chapter 2, Modules.

    PSReadLine provides command-line syntax highlighting, preserves history between sessions, and offers completion services when writing commands.

    PSReadLine can be configured to offer command completion based on previously typed commands, a useful feature when using similar commands in the console and one that can save searching history for the right command. By default, PSReadline 2.2.6 uses history and a command prediction plugin. The plugin may be explicitly enabled using

    Set-PSReadLineOption

    .

    Set-PSReadLineOption

    -PredictionSource

    HistoryAndPlugin

    Once enabled, PSReadLine will offer suggestions based on typed content that may be completed using Tab as shown in Figure 1.1.

    Figure 1.1: PSReadLine Predictive completion

    By default, Tab can be used to complete any command or parameter, and a variety of arguments for parameters. In addition to Tab completion, PSReadLine allows the use of Control and Space to provide menu style completion. For example, entering the following partial command:

    Get-ChildItem

    -

    Then pressing Control and Space (immediately after the hyphen) will show a menu that can be navigated using the cursor keys, as shown in Figure 1.2:

    Figure 1.2: PSReadLine List completion

    In PowerShell, the prompt displayed is controlled by a function named prompt. A very simple prompt can be set as shown below:

    function

    prompt

    {

    "

    $env:USERNAME

    $pwd

    PS>"

    }

    The default prompt can be restored by restarting PowerShell. A profile script is required to make changes on console restart. See

    about_profiles

    for more information:

    Get-Help about_profiles

    Several modules and tools exist to help customize prompts in PowerShell:

    PowerLine: https://github.com/Jaykul/PowerLine

    oh-my-posh: https://ohmyposh.dev/

    Starship: https://starship.rs/

    PowerShell is a complex language; a good editor can save time finding the right syntax to use in a script.

    PowerShell editors

    While PowerShell scripts can be written 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.

    Editors with explicit support for PowerShell, such as Visual Studio Code (VS Code with the PowerShell extension) and the PowerShell Studio editor 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 VS Code and PowerShell Studio, Windows PowerShell comes with the PowerShell ISE. The PowerShell ISE has not been updated for PowerShell 6 and higher and will only function correctly for the Windows PowerShell Desktop edition.

    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 and supports a wide variety of different languages. VS Code is an open-source editor that was published by Microsoft and can be downloaded from http://code.visualstudio.com. VS Code tends to be the editor of choice for many in the PowerShell community.

    The functionality of VS Code can be enhanced by using extensions from the marketplace: https://marketplace.visualstudio.com/VSCode. The Extension installer is part of the VS Code user interface, and the types of available extensions are shown in Figure 1.3:

    Figure 1.3: PowerShell extensions in VS Code

    The icons available on the left-hand side change depending on the extensions installed. A new installation of VS Code will show fewer icons than Figure 1.3.

    The PowerShell Extension should be installed. Other popular extensions include:

    Bracket Pair Colorizer 2

    Blockman

    Chocolatey

    Error Lens

    Live Share

    Prettify JSON

    Paid-for extensions, such as PowerShell Pro Tools, offer us the ability to design user interfaces in VS Code.

    The integrated console in VS Code can be used with all installed versions of PowerShell. The following screenshot shows how to change the version of PowerShell used when editing a script. Note the clickable version in the bottom-right corner:

    Figure 1.4: Choosing a PowerShell version

    The IntelliSense version provided by the editor will list and hint at the possible commands and parameters available. Help content is available to fill in the details.

    Getting help

    PowerShell includes a built-in help system accessible using the

    Get-Help

    command. Help content in PowerShell is often rich and detailed, frequently including multiple examples. 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?

    The command below shows a list of modules that support updatable help:

    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.

    The first time

    Get-Help

    runs, PowerShell prompts to update help.

    Computers with no internet access or computers behind a restrictive proxy server may not be able to download help content directly. The

    Save-Help

    command can be used in this scenario, which is discussed later in this section, to work around the problem.

    If PowerShell is unable to download help, it can only show a small amount of information about a command; for example, without downloading help, the content for the

    Out-Null

    command is minimal, as shown here:

    PS>

    Get-Help Out-Null NAME Out-Null SYNTAX Out-Null [-InputObject ] [] ALIASES None REMARKS Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. -- To download and install Help files for the module that includes this cmdlet, use Update-Help. -- To view the Help topic for this cmdlet online, type: Get-Help Out-Null -Online or go to http://go.microsoft.com/fwlink/?LinkID=113366.

    The help content in the preceding example is automatically generated by PowerShell. PowerShell inspects the command to determine which parameters are available.

    Updatable help as a

    help

    file can be viewed using the following command:

    Get-Help

    about_Updatable_Help

    Updateable help is not entirely free from issues. Internet resources change as content moves around over time, which may invalidate

    HelpInfoUri

    , the URL stored within the module and used to retrieve help files. For example, help for the

    Dism

    module was not available when this chapter was written.

    The Get-Help command

    When

    Get-Help

    is used without parameters, it shows introductory help about the help system. This content is taken from the default help file (

    Get-Help default

    ); a snippet of this is as follows:

    PS>

    Get-Help TOPIC PowerShell Help System SHORT DESCRIPTION Displays help about PowerShell cmdlets and concepts. LONG DESCRIPTION PowerShell Help describes Windows PowerShell cmdlets, functions,

    Help content can be long

    The help content, in most cases, does not fit on a single screen. The

    help

    command differs from

    Get-Help

    in that it pauses (waiting for a key to be pressed) after each page; for example:

    help default

    The previous command is equivalent to running

    Get-Help

    and piping it into the

    more

    command:

    Get-Help

    default | more

    Alternatively,

    Get-Help

    can be asked to show a window:

    Get-Help

    default

    -ShowWindow

    The available help content may be listed using either of the following two commands:

    Get-Help

    *

    Get-Help

    -Category

    All

    Help for a subject can be viewed as follows:

    Get-Help

    -Name

    For example, help for the

    Get-Variable

    command may be shown:

    Get-Help

    Get-Variable

    If a help document includes an online version link, it may be opened in a browser with the

    -Online

    parameter:

    Get-Help

    Get-Command

    -Online

    The URL used for online help can be viewed using

    Get-Command

    :

    Get-Command

    Get-Command

    |

    Select-Object

    HelpUri

    The help content is broken down into several sections: name, synopsis, syntax, description, related links, and remarks.

    Name simply includes the name of the command. Synopsis is a short description of the functionality provided by the command, often no more than one sentence. Description often provides much greater detail than synopsis. Related links and remarks are optional fields, which may include links to related content.

    Syntax is covered in the following section in more detail as it is the most complex part of the help document. A good understanding of the syntax allows quick evaluation of how to use a command, often removing the need to do more than skim help content.

    Syntax

    The syntax section lists each of the possible combinations of parameters a command accepts; each of these is known as a parameter set.

    A command that has more than one parameter set is shown in this example for the

    Get-Process

    command:

    SYNTAX

    Get-Process

    [[-

    Name

    ] <

    System.String

    []>] [-

    FileVersionInfo

    ] [-

    Module

    ] [<

    CommonParameters

    >]

    Get-Process

    [-

    FileVersionInfo

    ]

    -Id

    [-

    Module

    ] [<

    CommonParameters

    >]

    The syntax elements written in square brackets are optional; for example, syntax help for

    Get-Process

    shows that all its parameters are optional, as the following code shows:

    SYNTAX

    Get-Process

    [[-

    Name

    ] <

    System.String

    []>] [-

    FileVersionInfo

    ] [-

    Module

    ] [<

    CommonParameters

    >]

    As the

    Name

    parameter is optional,

    Get-Process

    may be run without any parameters. The command may also be run by specifying a value only and no parameter name. Alternatively, the parameter name can be included as well as the value.

    Each of the following examples is a valid use of

    Get-Process

    :

    Get-Process

    Get-Process

    pwsh

    Get-Process

    -Name

    pwsh

    Get-Command can show syntax

    Get-Command

    may be used to view the syntax for a command. For example, running the following command will show the same output as seen in the Syntax section of

    Get-Help

    :

    Get-Command Get-Variable -Syntax

    The different parameter types and how they are used are explored later in this chapter.

    Examples

    The Examples section of help provides working examples of how a command may be used. Help often includes more than one example.

    In some cases, a command is sufficiently complex that it requires a detailed example to accompany parameter descriptions; in others, the command is simple, and a good example may serve in lieu of reading the help documentation.

    PowerShell users can update help

    Help documentation for built-in commands is open source. If a cmdlet is missing helpful examples, they can be added.

    A link to the PowerShell-Docs repository is available at the bottom of the online help page. It should send you to the en-US version of help:

    https://github.com/MicrosoftDocs/PowerShell-Docs.

    Examples for a command can be requested by specifying the

    Examples

    parameter for

    Get-Help

    , as shown in the following example:

    Get-Help

    Get-Process

    -Examples

    The help information for most cmdlets usually includes several examples of their use, especially if the command has more than one parameter set.

    Parameter

    Parameters in PowerShell are used to supply named arguments to PowerShell commands.

    Help for specific parameters can be requested as follows:

    Get-Help

    Get-Command

    -Parameter

    The

    Parameter

    parameter allows for the quick retrieval of specific help for a single parameter; for example, help for the

    Path

    parameter of the

    Import-Csv

    command may be viewed:

    PS>

    Get-Help Import-Csv -Parameter Path -Path [] Specifies the path to the CSV file to import. You can also pipe a path to `Import-Csv`. Required? false Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false

    This avoids needing to scroll through a potentially large help file to see how to use just one parameter.

    The preceding content describes the parameter, whether the parameter is mandatory (

    Required

    ), its position, default value, pipeline behavior, and support for wildcards.

    Detailed and Full switches

    The

    Detailed

    switch parameter (a parameter that does not require an argument) asks

    Get-Help

    to return the most help content.

    The default sections returned by help are Name, Synopsis, Syntax, Description, Related Links, and Remarks.

    When

    Detailed

    is requested, Parameters and Examples are added. Related Links is excluded.

    The

    Detailed

    parameter is used as follows:

    Get-Help

    Get-Process

    -Detailed

    The

    Full

    switch parameter includes all the default sections, as well as Parameters, Inputs, Outputs, Notes, and Examples.

    The following code shows the sections detailing the input and output types for

    Get-Process

    from the full help document; content before those sections has been removed from this example:

    PS>

    Get-Help Get-Process -Full ... ... INPUTS System.Diagnostics.Process You can pipe a process object to Get-Process. OUTPUTS System.Diagnostics.Process By default, this cmdlet returns a System.Diagnostics.Process object. System.Diagnotics.FileVersionInfo If you use the FileVersionInfo parameter, this cmdlet returns a FileVersionInfo object. System.Diagnostics.ProcessModule If you use the Module parameter, without the FileVersionInfo parameter, this cmdlet returns a ProcessModule object.

    INPUTS

    is typically used to describe the value types that can be piped to a command. Pipelines are introduced in Chapter 4, Working with Objects in PowerShell.

    In addition to the extra sections, the

    Full

    switch parameter includes metadata in the parameter section, the same parameter metadata seen when using

    Get-Help Get-Process -Parameter Name

    .

    Help content in PowerShell is extensive and a valuable resource to have on any system running PowerShell.

    Save-Help

    The

    Save-Help

    command can be used with modules that support updatable help. It allows help content for installed modules to be saved to disk.

    Help for a module can be downloaded using the following command. The destination folder must exist before running the command:

    New-Item

    -Path

    C:\PSHelp

    -ItemType

    Directory

    Save-Help

    -Module

    Microsoft.PowerShell.Management

    -DestinationPath

    C:\PSHelp

    By default,

    Save-Help

    attempts to download help content for the current UI culture; that is, the current user interface language. The

    Get-UICulture

    command can be used to view the current culture, as the following example shows:

    PS>

    Get-UICulture LCID Name DisplayName ---- ---- ----------- 2057 en-GB English (United Kingdom)

    If help content is not available for that culture,

    Save-Help

    will not do anything and will not raise an error. For UI cultures other than

    en-US

    , the

    C:\PSHelp

    folder will likely be empty.

    Save-Help

    can be instructed to download help in a specific language by using the

    UICulture

    parameter:

    Save-Help

    -Module

    Microsoft.PowerShell.Management

    -DestinationPath

    C:\PSHelp

    -UICulture

    en

    -US

    If help content is available, it is downloaded as shown in the

    C:\PSHelp

    folder here:

    Figure 1.5: Downloaded help content for en-US

    By default,

    Save-Help

    (and

    Update-Help

    ) will not download help content more often than once every 24 hours as a rate-limiting control. This can be seen using the

    Verbose

    switch parameter:

    PS>

    Save-Help -Module Microsoft.PowerShell.Management -DestinationPath C:\PSHelp -UICulture en-US -Verbose VERBOSE: Help was not saved for the module Microsoft.PowerShell.Management, because the Save-Help command was run on this computer within the last 24 hours.

    The

    Verbose

    switch parameter is used to make any verbose messages the command author has included visible in the console.

    If help content is available for other cultures, and that content is downloaded immediately after

    en-US

    , then the

    Force

    parameter must be added:

    Save-Help

    -Module

    Microsoft.PowerShell.Management

    -DestinationPath

    C:\PSHelp

    -UICulture

    pl

    -PL

    -Force

    However, as help content for the

    Microsoft.PowerShell.Management

    module is only available in

    en-US

    , the preceding command displays an error message describing which cultures help is available for.

    Help content for all modules supporting updateable help can be saved as follows:

    Save-Help

    -DestinationPath

    C:\PSHelp

    -UICulture

    en

    -US

    Saved help content can be copied to another computer and imported using

    Update-Help

    . This technique is useful for computers that do not have internet access as it means help content can be made available.

    Update-Help

    The

    Update-Help

    command performs two tasks:

    Update help files on the local computer from the internet.

    Updates help files on the local computer from previously saved

    help

    files.

    To update help from the internet for all modules that support updateable help, run the

    Update-Help

    cmdlet with no parameters:

    Update-Help

    The

    Update-Help

    command includes a

    Scope

    parameter, which may be used to make help content available without needing Administrative access:

    Update-Help

    -Scope

    CurrentUser

    When the

    Scope

    parameter is set to

    CurrentUser

    , help content is downloaded to and read from (by

    Get-Help

    )

    $home\Documents\PowerShell\help

    . This path may be affected by folder redirection of the Documents folders, such as with services like OneDrive.

    The

    Scope

    parameter is not available in Windows PowerShell and administrative rights are required to update help content.

    For UI cultures other than

    en-US

    , the

    UICulture

    parameter may be required:

    Update-Help

    -UICulture

    en

    -US

    Like

    Save-Help

    ,

    Update-Help

    will not download help for a module more than once every 24 hours by default. This can be overridden by using the

    Force

    parameter:

    Update-Help

    -Name

    Microsoft.PowerShell.Management

    -Force

    -UICulture

    en

    -US

    Help content that was saved using

    Save-Help

    can be imported from a folder using the

    SourcePath

    parameter:

    Update-Help

    -SourcePath

    C:\PSHelp

    If the folder does not contain content for the current UI culture (shown with

    Get-UICulture

    ), an error message will be displayed:

    PS>

    Update-Help -Module Microsoft.PowerShell.Management -SourcePath C:\PSHelp Update-Help: Failed to update Help for the module(s) 'Microsoft.PowerShell.Management' with UI culture(s) {en-GB} : Unable to retrieve the HelpInfo XML file for UI culture en-GB. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again..

    The

    UICulture

    parameter can be used again to update help content from the folder:

    Update-Help

    -Module

    Microsoft.PowerShell.Management

    -SourcePath

    C:\PSHelp

    -UICulture

    en

    -US

    Help content is not limited to help for specific commands. PowerShell includes many topical help documents.

    About_* help files

    About_*

    documents describe features of the language or concepts that apply to more than one command. These items do not fit into help for individual commands.

    The list of help files can be viewed by running

    Get-Help

    with the category set to

    HelpFile

    , as demonstrated in the following code:

    Get-Help

    -Category

    HelpFile

    Alternatively, wildcards can be used with the

    Name

    parameter of

    Get-Help

    :

    Get-Help

    -Name

    About_*

    These help files cover a huge variety of topics ranging from aliases to modules to WMI. A number of these are shown here. The list will vary, depending on the modules installed on the computer running the command:

    Name Category Module Synopsis

    ----

    --------

    ------

    --------

    default HelpFile SHORT DESCRIPTION about_PSReadLine HelpFile about_Configuration HelpFile The Configuratio... about_Aliases HelpFile about_Alias_Provider HelpFile about_Arithmetic_Operators HelpFile about_Arrays HelpFile about_Assignment_Operators HelpFile about_Automatic_Variables HelpFile about_Break HelpFile

    Using help content is an important part of working with PowerShell. Memorizing content is not necessary where instructions and reference material are easily accessible.

    Get-Help

    may lead to finding a command to help achieve a task; however, it is often quicker to search using

    Get-Command

    .

    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 educated guesses about the names of commands so that there is little need to memorize long lists of commands. Commands use verbs to describe intent, and nouns to describe the target.

    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.

    The list of verbs can be seen 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.

    More commonly,

    Get

    and

    Set

    , or

    New

    and

    Remove

    commands may also be seen as complementary.

    Verb descriptions

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

    https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands?view=powershell-7.3&viewFallbackFrom=powershell-7.

    It is possible, although not recommended, to use verbs other than those in the approved list. If a command with an unapproved verb is written and included in a module, a warning message will be displayed every time the module is imported.

    Verbs are paired with nouns that describe the target of a command.

    Nouns

    A noun provides a very short description of the object the command is expecting to act on. The noun part may be a single word, as is the case with

    Get-Process

    ,

    New-Item

    , and

    Get-Help

    , or more than one word, as seen with

    Get-ChildItem

    ,

    Invoke-WebRequest

    , and

    Send-MailMessage

    .

    Command names often include a prefix on the noun. The Microsoft AD module uses the

    AD

    prefix. The Microsoft Graph modules are prefixed with the

    Mg

    prefix. Commands for managing the network components of the Windows operating system are prefixed with

    Net

    .

    Modules are explored in Chapter 2, Modules. As mentioned above, the commands used to manage the networking components of Windows use the

    Net

    prefix on every noun. This, in turn, allows the use of wildcards to search for commands.

    Finding commands

    The verb-noun pairing strives to make it easier to find commands without resorting to search engines.

    For example, if the goal was to list firewall rules, the following command may be used to show the

    Get

    commands that might affect the firewall:

    PS>

    Get-Command Get-*Firewall* CommandType Name Version Source ----------- ---- ------- ------ Function Get-NetFirewallAddressFilter 2.0.0.0 NetSecurity Function Get-NetFirewallApplicationFilter 2.0.0.0 NetSecurity Function Get-NetFirewallInterfaceFilter 2.0.0.0 NetSecurity Function Get-NetFirewallInterfaceTypeFilter 2.0.0.0 NetSecurity Function Get-NetFirewallPortFilter 2.0.0.0 NetSecurity Function Get-NetFirewallProfile 2.0.0.0 NetSecurity Function Get-NetFirewallRule 2.0.0.0 NetSecurity Function Get-NetFirewallSecurityFilter 2.0.0.0 NetSecurity Function Get-NetFirewallServiceFilter 2.0.0.0 NetSecurity Function Get-NetFirewallSetting 2.0.0.0 NetSecurity

    A wildcard might be used for the verb or the specific parameters for

    Verb

    and

    Noun

    might be used with

    Get-Command

    :

    Get-Command

    -Verb

    Get,

    Set

    -Noun

    *Firewall*

    The

    Get-Help

    command may also be used to find the list of commands above:

    Get-Help

    Get-*Firewall*

    As

    Get-Help

    also searches for help content, it is slower to use to search than

    Get-Command

    .

    The list of commands returned may vary, depending on the modules installed on the computer.

    From the preceding list,

    Get-NetFirewallRule

    closely matches the requirement (to see a list of firewall rules) and should be explored. Notice how each of the commands in the list above maintains the same prefix. This is a common naming practice in PowerShell.

    Once a potential command has been found,

    Get-Help

    can be used to assess whether the command is suitable.

    Aliases

    An alias in PowerShell is an alternate name for a command. A command may have more than one alias. Unlike languages like Bash, an alias cannot include parameters.

    The list of aliases can be viewed by using

    Get-Alias

    . The first few aliases are shown in the following example:

    PS>

    Get-Alias CommandType Name ----------- ---- Alias % -> ForEach-Object Alias ? -> Where-Object Alias ac -> Add-Content Alias cat -> Get-Content Alias cd -> Set-Location

    Get-Alias

    may be used to find the command behind an alias:

    Get-Alias

    dir

    The aliases available change depending on the operating system. For example, PowerShell on Linux omits aliases such as

    ac

    (

    Add-Content

    ),

    ls

    (

    Get-ChildItem

    ), and

    cat

    (

    Get-Content

    ).

    Get-Alias

    may also be used to find the aliases for any command:

    PS>

    Get-Alias -Definition Get-ChildItem CommandType Name Version Source ----------- ---- ------- ------ Alias dir -> Get-ChildItem Alias gci -> Get-ChildItem Alias ls -> Get-ChildItem

    Examples of aliases that are frequently used in examples on the internet include the following:

    %

    for

    ForEach-Object

    ?

    for

    Where-Object

    cd

    for

    Set-Location

    gc

    or

    cat

    for

    Get-Content

    ls

    or

    dir

    for

    Get-ChildItem

    irm

    for

    Invoke-WebRequest

    iex

    for

    Invoke-Expression

    An alias does not change how a command is used. There is no difference in the result of the following two commands:

    cd

    $env:TEMP

    Set-Location

    $env:TEMP

    New aliases are created with the

    New-Alias

    command. For example, an alias named

    grep

    for the

    Select-String

    command can be created as follows:

    New-Alias

    grep

    -Value

    Select-String

    Aliases can be removed using the

    Remove-Alias

    command, including default aliases such as

    ls

    :

    Remove-Alias

    grep

    Aliases may also be removed using

    Remove-Item

    as an alternative to

    Remove-Alias

    :

    Remove-Item

    alias:\grep

    Aliases created in one session are not remembered when a new PowerShell session is started.

    More information is available about aliases in the help file

    about_Aliases

    . The help file is viewed using the following command:

    Get-Help

    about_Aliases

    As mentioned above, aliases do not persist between PowerShell sessions (when the console is restarted). Profile scripts can be used to make an alias (or any other preferences) available when PowerShell is restarted.

    About profile scripts

    Aliases do not persist across PowerShell sessions. A profile script is often used for user-specific preferences like this.

    Profiles are where most user-specific shell customization takes place, from changing prompts and default settings to loading modules to creating aliases.

    Shell customization with profile scripts is an enormously involved and highly personal topic. This section provides a brief introduction to the topic only.

    PowerShell has four different profile paths – two are user-specific and two are machine-specific. The profile paths are also dependent on the host – one user and one machine path are specific to the terminal that started PowerShell.

    The profile paths are described by the built-in variable

    $profile

    . The

    Select-Object *

    command is used to show all the possible values in the example below:

    PS>

    $profile

    | Select-Object * AllUsersAllHosts : C:\Program Files\PowerShell\7\profile.ps1 AllUsersCurrentHost : C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1 CurrentUserAllHosts : C:\Users\user\Documents\PowerShell\profile.ps1 CurrentUserCurrentHost : C:\Users\user\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

    If the same command is run in the VS Code integrated terminal, the two host-specific paths will differ:

    PS>

    $profile

    | Select-Object * AllUsersAllHosts : C:\Program Files\PowerShell\7\profile.ps1 AllUsersCurrentHost : C:\Program Files\PowerShell\7\Microsoft.VSCode_profile.ps1 CurrentUserAllHosts : C:\Users\user\Documents\PowerShell\profile.ps1 CurrentUserCurrentHost : C:\Users\user\Documents\PowerShell\Microsoft.VSCode_profile.ps1

    PowerShell will run each of the profile scripts where the script exists. If the script does not exist, the path is ignored.

    Starting PowerShell with the

    -NoProfile

    switch avoids loading profile script files, a useful parameter for any scheduled scripts, or for testing to see if the profile is causing a problem.

    The paths used above may not exist at all. To create a profile script, create the directory first, if necessary, then save the script file using one of the names and paths above.

    The about document for profiles explores this topic further:

    Get-Help about_profiles

    A variety of different tools are available to customize the look and feel, which are typically started from a profile script. Customization of the prompt is a common activity:

    PowerLine: https://github.com/Jaykul/PowerLine

    oh-my-posh: https://ohmyposh.dev/

    Sarship: https://starship.rs/

    The Windows Terminal customized prompts article makes use of oh-my-posh in an example setup:

    https://learn.microsoft.com/en-us/windows/terminal/tutorials/custom-prompt-setup.

    Finally, for users with multiple computers, the chezmoi tool might be used to ensure all computers use the same configuration:

    https://www.chezmoi.io/.

    Commands (and aliases) use parameters to pass arguments into a command.

    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 by square brackets. If a parameter is used, a value (or argument) must be supplied. A fragment of the syntax for

    Get-Help

    is shown below. It shows that a

    Category

    parameter is available and that the parameter is optional.

    SYNTAX

    Get-Help

    ... [-

    Category

    <

    string

    []>] ...

    If a value for the

    Category

    parameter is to be used, the name of the parameter must also be specified. This is shown in the following example:

    Get-Help

    -Category

    HelpFile

    The command above filters help documents to help files, the about documents.

    Optional positional parameters

    An optional positional parameter is surrounded by square brackets, like an optional parameter. In addition, the parameter name itself is enclosed in square brackets. This indicates that the parameter is optional and that if it is used, the parameter and value can be supplied, or just the value without the parameter name.

    It is not uncommon to see an optional positional parameter as the first parameter:

    SYNTAX

    Get-Process

    [[-

    Name

    ] <

    string

    []>] ...

    In this example, either of the following may be used:

    Get-Process

    -Name

    pwsh

    Get-Process

    pwsh

    The output from the two commands is identical. This includes the parameter name, which, even when it is optional, is less ambiguous and therefore a recommended practice.

    Mandatory parameters

    A mandatory parameter must always be supplied and is written as follows:

    SYNTAX

    Get-ADUser

    -Filter

    ...

    In this case, the

    Filter

    parameter name must be used, and it must be given a value. For example, to supply a

    Filter

    for the command, the

    Filter

    parameter must be explicitly written:

    Get-ADUser

    -Filter

    'sAMAccountName -eq SomeName'

    The

    Get-ADUser

    command has a second parameter set that uses a different parameter name with a positional value.

    Mandatory positional parameters

    Mandatory parameters must always be supplied, but in some cases, it is possible to supply the value without using the parameter name. The parameter the value applies to is based on position.

    Parameters that are mandatory and accept values based on position are written with the parameter name only in square brackets, as shown here:

    SYNTAX

    Get-ADUser

    [-

    Identity

    ] ...

    In this case, the

    Identity

    parameter name is optional, but the value is not. This command may be used as described by either of the following examples:

    Get-ADUser

    -Identity

    useridentity

    Get-ADUser

    useridentity

    In both

    Enjoying the preview?
    Page 1 of 1