Mastering PowerShell Scripting - Fourth Edition

Book description

This complete guide takes you on a tour of PowerShell from the basics to its advanced functionality, helping you automate your tedious and time-consuming system admin tasks

Key Features

  • Automate complex tasks, manipulate data, and secure your environment
  • Work with dual code for PowerShell 7 and Windows PowerShell to maintain compatibility with older versions
  • See PowerShell in action, from learning the fundamentals to creating classes, scripts, and modules

Book Description

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

What you will learn

  • Optimize code with functions, switches, and looping structures
  • Test and debug your scripts as well as raising and catching errors
  • Work with objects and operators to test and manipulate data
  • Parse and manipulate different data types
  • Use jobs, runspaces, and runspace pools to run code asynchronously
  • Write .NET classes with ease within PowerShell
  • Create and implement regular expressions in PowerShell scripts
  • Make use of advanced techniques to define and restrict the behavior of parameters

Who this book is for

This book is for system administrators who want to automate and speed up their processes using PowerShell and Windows PowerShell. You’ll need to know the basics of operating systems, but beginners with no prior experience with PowerShell will have no trouble following along.

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. Introduction to PowerShell
    1. What is PowerShell?
    2. PowerShell editors
    3. Getting help
      1. Updatable help
      2. The Get-Help command
        1. Syntax
        2. Examples
        3. Parameter
        4. Detailed and Full switches
      3. Save-Help
      4. Update-Help
      5. About_* help files
    4. Command naming and discovery
      1. Verbs
      2. Nouns
      3. Finding commands
      4. Aliases
    5. Parameters, values, and parameter sets
      1. Parameters
        1. Optional parameters
        2. Optional positional parameters
        3. Mandatory parameters
        4. Mandatory positional parameters
        5. Switch parameters
      2. Parameter values
      3. Parameter sets
      4. Common parameters
      5. Confirm and WhatIf
        1. Confirm and ConfirmPreference
        2. WhatIf and WhatIfPreference
      6. Force parameter
      7. PassThru parameter
    6. Introduction to providers
      1. Drives and providers
    7. Introduction to splatting
      1. Splatting to avoid long lines
      2. Conditional use of parameters
      3. Splatting to avoid repetition
      4. Splatting and positional parameters
    8. Parser modes
    9. Experimental features
    10. Summary
  3. Modules and Snap-Ins
    1. Introducing modules
      1. The Get-Module command
      2. The Import-Module command
      3. The Remove-Module command
      4. PSModulePath in PowerShell
      5. Using Windows PowerShell modules in PowerShell 7
    2. Finding and installing modules
      1. What is the PowerShell Gallery?
      2. The Find-Module command
      3. The Install-Module command
      4. The Update-Module command
      5. The Save-Module command
    3. PowerShellGet 3.0
      1. Repositories
      2. Version ranges
    4. PowerShell repositories
      1. Creating an SMB repository
      2. NuGet repositories
    5. About snap-ins
    6. Summary
  4. Working with Objects in PowerShell
    1. Pipelines
      1. Standard output
      2. Non-standard output
      3. The object pipeline
    2. Members
      1. The Get-Member command
      2. Accessing object properties
      3. Access modifiers
      4. Using methods
      5. The Add-Member command
    3. Enumerating and filtering
      1. The ForEach-Object command
        1. Begin and End parameters
        2. The Parallel parameter
        3. The MemberName parameter
      2. The Where-Object command
    4. Selecting and sorting
      1. The Select-Object command
        1. Calculated properties
        2. The ExpandProperty parameter
        3. The Unique parameter
        4. Property sets
      2. The Sort-Object command
    5. Grouping and measuring
      1. The Group-Object command
      2. The Measure-Object command
    6. Comparing
    7. Importing, exporting, and converting
      1. The Export-Csv command
      2. The Import-Csv command
      3. Export-Clixml and Import-Clixml
      4. The Tee-Object command
    8. Summary
  5. Operators
    1. Arithmetic operators
      1. Operator precedence
      2. Addition and subtraction operators
        1. Addition operator
        2. Subtraction operator
      3. Multiplication, division, and remainder operators
        1. Multiplication operator
        2. Division operator
        3. Remainder operator
    2. Assignment operators
      1. Assign, add and assign, and subtract and assign
      2. Multiply and assign, divide and assign, and modulus and assign
      3. Statements can be assigned to a variable
    3. Comparison operators
      1. Case sensitivity
      2. Comparison operators and arrays
      3. Comparisons to null
      4. Equal to and not equal to
      5. Like and not like
      6. Greater than and less than
      7. Contains and in
    4. Regular expression-based operators
      1. Match and not match
      2. Replace
      3. Split
    5. Logical operators
      1. And
      2. Or
      3. Exclusive or
      4. Not
    6. Binary operators
      1. Binary and
      2. Binary or
      3. Binary exclusive or
      4. Binary not
      5. Shift left and shift right operators
    7. Type operators
      1. As
      2. is and isnot
    8. Redirection operators
      1. Redirection to a file
      2. Redirecting streams to standard output
      3. Redirection to null
    9. Other operators
      1. Call
      2. Comma
      3. Format
      4. Increment and decrement
      5. Join
      6. Ternary
      7. Null coalescing
      8. Null coalescing assignment
      9. Null conditional
      10. Pipeline chain
      11. Background
    10. Summary
  6. Variables, Arrays, and Hashtables
    1. Naming and creating variables
    2. Objects assigned to variables
    3. Variable commands
      1. Clear-Variable
      2. Get-Variable
      3. New-Variable
      4. Remove-Variable
      5. Set-Variable
    4. Variable provider
    5. Scopes and variables
      1. Accessing variables
      2. Scope modifiers
      3. Numeric scopes
      4. Private variables
    6. Types and type conversion
      1. Typed numeric values
    7. Arrays
      1. Creating an array
      2. Arrays with a type
      3. Adding elements to an array
      4. Selecting elements from an array
      5. Changing element values in an array
      6. Removing elements
        1. Removing elements by index
        2. Removing elements by value
      7. Clearing an array
      8. Filling variables from arrays
      9. Multi-dimensional and jagged arrays
    8. Hashtables
      1. Creating a Hashtable
      2. Adding and changing Hashtable elements
      3. Selecting elements from a Hashtable
      4. Enumerating a Hashtable
      5. Removing elements from a Hashtable
    9. Lists, dictionaries, queues, and stacks
      1. System.Collections.Generic.List
        1. Creating a list
        2. Adding elements to the list
        3. Selecting elements from the list
        4. Removing elements from the list
        5. Changing element values in a list
      2. System.Collections.Generic.Dictionary
        1. Creating a dictionary
        2. Adding and changing elements in a dictionary
        3. Selecting elements from a dictionary
        4. Enumerating a dictionary
        5. Removing elements from a dictionary
      3. System.Collections.Generic.Queue
        1. Creating a queue
        2. Enumerating the queue
        3. Adding elements to the queue
        4. Removing elements from the queue
      4. System.Collections.Generic.Stack
        1. Creating a stack
        2. Enumerating the stack
        3. Adding elements to the stack
        4. Removing elements from the stack
    10. Summary
  7. Conditional Statements and Loops
    1. if, else, and elseif
      1. Assignment within if statements
    2. switch
      1. switch and arrays
      2. switch and files
      3. wildcard and regex
      4. Script block cases
      5. Switch, break, and continue
    3. Loops
      1. Foreach loop
      2. for loop
      3. do until and do while loops
      4. While loop
    4. Loops, break, and continue
      1. Break and continue outside loops
      2. Loops and labels
    5. Implicit Boolean
    6. Summary
  8. Working with .NET
    1. Assemblies
      1. About the Global Assembly Cache
    2. Types
    3. Enumerations
    4. Classes
    5. Namespaces
    6. The using keyword
      1. Using namespaces
      2. Using assemblies
    7. Type accelerators
    8. Members
      1. Constructors
      2. Properties
      3. Methods
        1. Fluent interfaces
      4. Static methods
        1. About the new method
      5. Static properties
    9. Reflection in PowerShell
      1. The TypeAccelerators type
      2. The ArgumentTypeConverterAttribute type
    10. Summary
  9. Strings, Numbers, and Dates
    1. Manipulating strings
      1. Indexing into strings
      2. Substring
      3. Split
      4. Replace
      5. Trim, TrimStart, and TrimEnd
      6. Insert and Remove
      7. IndexOf and LastIndexOf
      8. PadLeft and PadRight
      9. ToUpper, ToLower, and ToTitleCase
      10. Contains, StartsWith, and EndsWith
      11. String methods and arrays
      12. Chaining methods
    2. Converting strings
      1. The *-Csv commands
      2. ConvertFrom-StringData
      3. Convert-String
      4. ConvertFrom-String
      5. Working with Base64
    3. Manipulating numbers
      1. Large byte values
      2. Power of 10
      3. Hexadecimal
      4. Using System.Math
      5. Converting strings into numeric values
    4. Manipulating dates and times
      1. Parsing dates
      2. Changing dates
      3. DateTime parameters
      4. Comparing dates
    5. Summary
  10. Regular Expressions
    1. Regex basics
      1. Literal characters
      2. Any character (.)
      3. Repetition with * and +
      4. The escape character (\)
      5. Optional characters
      6. Non-printable characters
      7. Debugging regular expressions
    2. Anchors
    3. Quantifiers
      1. Exploring the quantifiers
    4. Character classes
      1. Ranges
      2. Negated character class
      3. Character class subtraction
      4. Shorthand character classes
      5. Unicode category class
    5. Alternation
    6. Grouping
      1. Repeating groups
      2. Restricting alternation
      3. Capturing values
        1. Named capture groups
        2. Non-capturing groups
    7. Look-ahead and look-behind
    8. The .NET Regex type
    9. Regex options
    10. Examples of regular expressions
      1. MAC addresses
      2. IP addresses
      3. The netstat command
      4. Formatting certificates
    11. Summary
  11. Files, Folders, and the Registry
    1. Working with providers
      1. Navigating
      2. Getting items
      3. Drives
      4. Creating providers
    2. Items
      1. Testing for existing items
      2. Creating and deleting items
      3. Invoking items
      4. Item properties
        1. Properties and the filesystem
        2. Adding and removing file attributes
      5. Registry values
    3. Windows permissions
      1. Access and audit
      2. Rule protection
      3. Inheritance and propagation flags
      4. Removing ACEs
      5. Copying lists and entries
      6. Adding ACEs
        1. Filesystem rights
        2. Registry rights
        3. Numeric values in the ACL
      7. Ownership
    4. Transactions
    5. File catalog commands
      1. New-FileCatalog
      2. Test-FileCatalog
    6. Summary
  12. Windows Management Instrumentation
    1. Working with WMI
      1. WMI classes
      2. WMI commands
    2. CIM cmdlets
      1. Getting instances
      2. Getting classes
      3. Calling methods
      4. Creating instances
      5. Working with CIM sessions
      6. Associated classes
    3. The WMI Query Language
      1. Understanding SELECT, WHERE, and FROM
      2. Escape sequences and wildcards
      3. Logic operators
      4. Comparison operators
      5. Quoting values
      6. Associated classes
        1. WMI object paths
        2. Using ASSOCIATORS OF
    4. WMI Type Accelerators
      1. Getting instances
      2. Working with dates
      3. Getting classes
      4. Calling methods
      5. Creating instances
      6. Associated classes
    5. Permissions
      1. Sharing permissions
        1. Creating a shared directory
        2. Getting a security descriptor
        3. Adding an access control entry
        4. Setting the security descriptor
      2. WMI permissions
        1. Getting a security descriptor
        2. The access mask
      3. WMI and SDDL
    6. Summary
  13. Working with HTML, XML, and JSON
    1. HTML
      1. ConvertTo-Html
      2. Multiple tables
      3. Adding style
      4. HTML and special characters
    2. XML commands
      1. About XML
        1. Elements and attributes
        2. Namespaces
        3. Schemas
      2. Select-Xml
      3. Select-Xml and namespaces
      4. ConvertTo-Xml
    3. System.Xml
      1. The XML type accelerator
      2. XPath and XmlDocument
      3. Working with namespaces
      4. Creating XML documents
      5. Modifying element and attribute values
      6. Adding elements
      7. Removing elements and attributes
      8. Copying nodes between documents
      9. Schema validation
      10. Infer a schema
    4. System.Xml.Linq
      1. Opening documents
      2. Selecting nodes
      3. Creating documents
      4. Working with namespaces
      5. Modifying element and attribute values
      6. Adding nodes
      7. Removing nodes
      8. Schema validation
    5. JSON
      1. ConvertTo-Json
        1. EnumsAsStrings
        2. AsArray
        3. EscapeHandling
      2. ConvertFrom-Json
        1. AsHashtable
        2. NoEnumerate
    6. Summary
  14. Web Requests and Web Services
    1. Technical requirements
    2. Web requests
      1. HTTP methods
      2. HTTPS
      3. Bypassing SSL errors in Windows PowerShell
      4. Capturing SSL errors
    3. Working with REST
      1. Invoke-RestMethod
      2. Simple requests
      3. Requests with arguments
      4. Working with paging
      5. Working with authentication
      6. Using basic authentication
      7. OAuth
        1. Creating an application
        2. Getting an authorization code
        3. OAuth browser issues
        4. Requesting an access token
        5. Using a token
    4. Working with SOAP
      1. Finding a SOAP service
      2. SOAP in Windows PowerShell
        1. New-WebServiceProxy
        2. Methods
        3. Methods and enumerations
        4. Methods and SOAP objects
        5. Overlapping services
      3. SOAP in PowerShell 7
        1. Getting the WSDL document
        2. Discovering methods and enumerations
        3. Running methods
    5. Summary
  15. Remoting and Remote Management
    1. Technical requirements
    2. WS-Management
      1. Enabling remoting
      2. Get-WSManInstance
      3. The WSMan drive
      4. Remoting and SSL
        1. Set-WSManQuickConfig
      5. Remoting and permissions
        1. Remoting permissions GUI
        2. Remoting permissions by script
      6. User Account Control
      7. Trusted hosts
    3. PSSessions
      1. New-PSSession
      2. Get-PSSession
      3. Invoke-Command
        1. Local functions and remote sessions
        2. Using splatting with ArgumentList
        3. The AsJob parameter
        4. Disconnected sessions
        5. The using variable scope
      4. The Enter-PSSession command
      5. Import-PSSession
      6. Export-PSSession
      7. Copying items between sessions
    4. Remoting on Linux
    5. Remoting over SSH
      1. Connecting from Windows to Linux
      2. Connecting from Linux to Windows
    6. The double-hop problem
      1. CredSSP
      2. Passing credentials
    7. CIM sessions
      1. New-CimSession
      2. Get-CimSession
      3. Using CIM sessions
    8. Just Enough Administration
      1. Session configuration
      2. Role capabilities
    9. Summary
  16. Asynchronous Processing
    1. Working with jobs
      1. The Start-Job, Get-Job, and Remove-Job commands
      2. The Receive-Job command
      3. The Wait-Job command
      4. Jobs and the using scope modifier
      5. The background operator
      6. The ThreadJob module
      7. Batching jobs
    2. Reacting to events
      1. The Register-ObjectEvent and *-Event commands
      2. The Get-EventSubscriber and Unregister-Event commands
      3. The Action, Event, EventArgs, and MessageData parameters
    3. Using runspaces and runspace pools
      1. Creating a PowerShell instance
      2. The Invoke and BeginInvoke methods
      3. The EndInvoke method and the PSDataCollection object
      4. Running multiple instances
      5. Using the RunspacePool object
      6. About the InitialSessionState object
        1. Adding modules and snap-ins
        2. Adding variables
        3. Adding functions
      7. Using the InitialSessionState and RunspacePool objects
      8. Using Runspace-synchronized objects
    4. Summary
  17. Graphical User Interfaces
    1. About Windows Presentation Foundation (WPF)
    2. Designing a UI
    3. About XAML
    4. Displaying the UI
    5. Layout
      1. Using the Grid control
      2. Using the StackPanel control
      3. Using the DockPanel control
      4. About Margin and Padding
    6. Naming and locating elements
    7. Handling events
      1. Buttons and the Click event
      2. ComboBox and SelectionChanged
      3. Adding elements programmatically
      4. Sorting a ListView
    8. Responsive interfaces
      1. Import-Xaml and Runspace support
      2. Using the Dispatcher
    9. Summary
  18. Scripts, Functions, and Script Blocks
    1. About style
    2. Capabilities of scripts, functions, and script blocks
      1. Scripts and using statements
      2. Scripts and Requires
      3. Nesting functions
      4. Script blocks and closures
    3. Parameters and the param block
      1. Parameter types
      2. Default values
      3. Cross-referencing parameters
    4. The CmdletBinding attribute
      1. Common parameters
      2. CmdletBinding properties
      3. ShouldProcess and ShouldContinue
        1. ShouldProcess
        2. ShouldContinue
    5. The Alias attribute
    6. begin, process, end, and cleanup
      1. begin
      2. process
      3. end
      4. cleanup
      5. Named blocks and return
    7. Managing output
      1. The Out-Null command
      2. Assigning to null
      3. Redirecting to null
      4. Casting to Void
    8. Working with long lines
      1. Line break after a pipe
      2. Line break after an operator
      3. Using the array operator to break up lines
    9. Comment-based help
      1. Parameter help
      2. Examples
    10. Summary
  19. Parameters, Validation, and Dynamic Parameters
    1. The Parameter attribute
      1. Position and positional binding
      2. The DontShow property
      3. The ValueFromRemainingArguments property
      4. The HelpMessage property
    2. Validating input
      1. The PSTypeName attribute
      2. Validation attributes
        1. The ValidateNotNull attribute
        2. The ValidateNotNullOrEmpty attribute
        3. The ValidateCount attribute
        4. The ValidateDrive attribute
        5. The ValidateUserDrive attribute
        6. The ValidateLength attribute
        7. The ValidatePattern attribute
        8. The ValidateRange attribute
        9. The ValidateScript attribute
        10. The ValidateSet attribute
      3. The Allow attributes
        1. The AllowNull attribute
        2. The AllowEmptyString attribute
        3. The AllowEmptyCollection attribute
      4. PSReference parameters
    3. Pipeline input
      1. About ValueFromPipeline
      2. Accepting null input
      3. Input object types
      4. Using ValueFromPipeline for multiple parameters
      5. Using PSTypeName
      6. About ValueFromPipelineByPropertyName
      7. ValueFromPipelineByPropertyName and parameter aliases
    4. Defining parameter sets
    5. Argument completers
      1. The ArgumentCompleter attribute
      2. Using Register-ArgumentCompleter
      3. Listing registered argument completers
    6. Dynamic parameters
      1. Creating a RuntimeDefinedParameter object
      2. Using RuntimeDefinedParameterDictionary
      3. Using dynamic parameters
      4. Conditional parameters
    7. Summary
  20. Classes and Enumerations
    1. Defining an enumeration
      1. Enum and underlying types
      2. Automatic value assignment
      3. Enum or ValidateSet
      4. The Flags attribute
      5. Using enumerations to convert a value
    2. Creating a class
      1. Properties
      2. Constructors
      3. Methods
      4. The Hidden modifier
      5. The Static modifier
      6. Inheritance
        1. Constructors and inheritance
        2. Calling methods in a parent class
      7. Working with interfaces
        1. Implementing IComparable
        2. Implementing IEquatable
      8. Supporting casting
    3. Classes for parameters
      1. Argument-transformation attribute classes
      2. Validation attribute classes
        1. ValidateArgumentsAttribute
        2. ValidateEnumeratedArgumentsAttribute
      3. Classes for ValidateSet
    4. Classes and DSC
      1. Implementing Get
      2. Implementing Set
      3. Implementing Test
      4. Using the resource
    5. Summary
  21. Building Modules
    1. Technical requirements
    2. Creating a module
      1. The root module
      2. Export-ModuleMember
      3. Module manifests
        1. Test-ModuleManifest
        2. Update-ModuleManifest
    3. Publishing a module
      1. Publishing and side-by-side versioning
    4. Multi-file module layout
      1. Dot sourcing module content
      2. Merging module content
      3. ModuleBuilder and DSC resources
    5. Module scope
      1. Accessing module scope
      2. Modules, classes, and enumerations
    6. Initializing and removing modules
      1. The ScriptsToProcess property
      2. The OnRemove event
    7. Summary
  22. Testing
    1. Technical requirements
    2. Static analysis
      1. PSScriptAnalyzer
        1. Configurable rules
        2. Suppressing rules
      2. Using AST
        1. Visualizing the AST
        2. Searching the AST
      3. Tokenizer
      4. Custom script analyzer rules
        1. Creating a custom rule
        2. AST-based rules
        3. Token-based rules
    3. Testing with Pester
      1. Testing methodologies
      2. What to test
      3. Describing tests
        1. About the Describe and Context keywords
        2. About the It keyword
      4. Should and assertions
        1. Testing for errors
      5. Iteration with Pester
        1. Using the TestCases parameter
        2. Using the ForEach parameter
      6. Conditional testing
        1. Using Set-ItResult
        2. Using Skip
      7. Pester phases
      8. Before and After blocks
      9. Mocking commands
        1. Parameter filtering
        2. Overriding mocks
        3. Mocking non-local commands
      10. Mocking objects
        1. Adding methods to PSCustomObject
        2. Disarming .NET types
        3. Mocking CIM objects
      11. InModuleScope
        1. Pester in scripts
    4. Summary
  23. Error Handling
    1. Error types
      1. Non-terminating errors
      2. Terminating errors
    2. Error actions
      1. About Get-Error
    3. Raising errors
      1. Error records
      2. Raising non-terminating errors
        1. Using the WriteError method
      3. Raising terminating errors
        1. Using the ThrowTerminatingError method
    4. Catching errors
      1. ErrorVariable
      2. try, catch, and finally
      3. Rethrowing errors
      4. Inconsistent error handling
      5. throw and ErrorAction
      6. Nesting try, catch, and finally
      7. About trap
        1. Using trap
        2. trap, scope, and continue
    5. Summary
  24. Debugging and Troubleshooting
    1. Common problems
      1. Dash characters
      2. Operator usage
        1. Assignment instead of equality
        2. -or instead of -and
        3. Negated array comparisons
      3. Use of named blocks
        1. Code outside of a named block
        2. Pipeline without process
      4. Problems with variables
        1. About strict mode
        2. Variables and types
        3. Types and reserved variables
    2. Debugging in the console
      1. Setting a command breakpoint
      2. Using variable breakpoints
      3. Setting a line breakpoint
    3. Debugging in Visual Studio Code
      1. Using the debugger
      2. Viewing the CALL STACK
      3. Using launch configurations
      4. Using WATCH
    4. Summary
  25. Other Books You May Enjoy
  26. Index

Product information

  • Title: Mastering PowerShell Scripting - Fourth Edition
  • Author(s): Chris Dent
  • Release date: June 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781800206540