Mastering PowerShell Scripting: Automate and manage your environment using PowerShell 7.1, [4 ed.]
1800206542, 9781800206540
This complete guide takes you on a tour of PowerShell from the basics to its advanced functionality, helping you automat
156
21
11MB
English
Pages 788
[789]
Year 2021
Report DMCA / Copyright
DOWNLOAD PDF FILE
Table of contents :
Copyright
Contributors
Table of Contents
Preface
Chapter 1: Introduction to PowerShell
What is PowerShell?
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
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
Chapter 2: Modules and Snap-Ins
Introducing modules
The Get-Module command
The Import-Module command
The Remove-Module command
PSModulePath in PowerShell
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
PowerShellGet 3.0
Repositories
Version ranges
PowerShell repositories
Creating an SMB repository
NuGet repositories
About snap-ins
Summary
Chapter 3: 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
The Add-Member command
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
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
Summary
Chapter 4: Operators
Arithmetic operators
Operator precedence
Addition and subtraction operators
Addition operator
Subtraction operator
Multiplication, division, and remainder operators
Multiplication operator
Division operator
Remainder operator
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
Comparison operators
Case sensitivity
Comparison operators and arrays
Comparisons to null
Equal to and not equal to
Like and not like
Greater than and less than
Contains and in
Regular expression-based operators
Match and not match
Replace
Split
Logical operators
And
Or
Exclusive or
Not
Binary operators
Binary and
Binary or
Binary exclusive or
Binary not
Shift left and shift right operators
Type operators
As
is and isnot
Redirection operators
Redirection to a file
Redirecting streams to standard output
Redirection to null
Other operators
Call
Comma
Format
Increment and decrement
Join
Ternary
Null coalescing
Null coalescing assignment
Null conditional
Pipeline chain
Background
Summary
Chapter 5: Variables, Arrays, and Hashtables
Naming and creating variables
Objects assigned to variables
Variable commands
Clear-Variable
Get-Variable
New-Variable
Remove-Variable
Set-Variable
Variable provider
Scopes and variables
Accessing variables
Scope modifiers
Numeric scopes
Private variables
Types and type conversion
Typed numeric values
Arrays
Creating an array
Arrays with a type
Adding elements to an array
Selecting elements from an array
Changing element values in an array
Removing elements
Removing elements by index
Removing elements by value
Clearing an array
Filling variables from arrays
Multi-dimensional and jagged arrays
Hashtables
Creating a Hashtable
Adding and changing Hashtable elements
Selecting elements from a Hashtable
Enumerating a Hashtable
Removing elements from a Hashtable
Lists, dictionaries, queues, and stacks
System.Collections.Generic.List
Creating a list
Adding elements to the list
Selecting elements from the list
Removing elements from the list
Changing element values in a list
System.Collections.Generic.Dictionary
Creating a dictionary
Adding and changing elements in a dictionary
Selecting elements from a dictionary
Enumerating a dictionary
Removing elements from a dictionary
System.Collections.Generic.Queue
Creating a queue
Enumerating the queue
Adding elements to the queue
Removing elements from the queue
System.Collections.Generic.Stack
Creating a stack
Enumerating the stack
Adding elements to the stack
Removing elements from the stack
Summary
Chapter 6: Conditional Statements and Loops
if, else, and elseif
Assignment within if statements
switch
switch and arrays
switch and files
wildcard and regex
Script block cases
Switch, break, and continue
Loops
Foreach loop
for loop
do until and do while loops
While loop
Loops, break, and continue
Break and continue outside loops
Loops and labels
Implicit Boolean
Summary
Chapter 7: Working with .NET
Assemblies
About the Global Assembly Cache
Types
Enumerations
Classes
Namespaces
The using keyword
Using namespaces
Using assemblies
Type accelerators
Members
Constructors
Properties
Methods
Fluent interfaces
Static methods
About the new method
Static properties
Reflection in PowerShell
The TypeAccelerators type
The ArgumentTypeConverterAttribute type
Summary
Chapter 8: Strings, Numbers, and Dates
Manipulating strings
Indexing into strings
Substring
Split
Replace
Trim, TrimStart, and TrimEnd
Insert and Remove
IndexOf and LastIndexOf
PadLeft and PadRight
ToUpper, ToLower, and ToTitleCase
Contains, StartsWith, and EndsWith
String methods and arrays
Chaining methods
Converting strings
The *-Csv commands
ConvertFrom-StringData
Convert-String
ConvertFrom-String
Working with Base64
Manipulating numbers
Large byte values
Power of 10
Hexadecimal
Using System.Math
Converting strings into numeric values
Manipulating dates and times
Parsing dates
Changing dates
DateTime parameters
Comparing dates
Summary
Chapter 9: Regular Expressions
Regex basics
Literal characters
Any character (.)
Repetition with * and +
The escape character (\)
Optional characters
Non-printable characters
Debugging regular expressions
Anchors
Quantifiers
Exploring the quantifiers
Character classes
Ranges
Negated character class
Character class subtraction
Shorthand character classes
Unicode category class
Alternation
Grouping
Repeating groups
Restricting alternation
Capturing values
Named capture groups
Non-capturing groups
Look-ahead and look-behind
The .NET Regex type
Regex options
Examples of regular expressions
MAC addresses
IP addresses
The netstat command
Formatting certificates
Summary
Chapter 10: Files, Folders, and the Registry
Working with providers
Navigating
Getting items
Drives
Creating providers
Items
Testing for existing items
Creating and deleting items
Invoking items
Item properties
Properties and the filesystem
Adding and removing file attributes
Registry values
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
New-FileCatalog
Test-FileCatalog
Summary
Chapter 11: Windows Management Instrumentation
Working with WMI
WMI classes
WMI commands
CIM cmdlets
Getting instances
Getting classes
Calling methods
Creating instances
Working with CIM sessions
Associated classes
The WMI Query Language
Understanding SELECT, WHERE, and FROM
Escape sequences and wildcards
Logic operators
Comparison 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
Chapter 12: Working with HTML, XML, and JSON
HTML
ConvertTo-Html
Multiple tables
Adding style
HTML and special characters
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
Working with namespaces
Creating XML documents
Modifying element and attribute values
Adding elements
Removing elements and attributes
Copying nodes between documents
Schema validation
Infer 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
Summary
Chapter 13: Web Requests and Web Services
Technical requirements
Web requests
HTTP methods
HTTPS
Bypassing SSL errors in Windows PowerShell
Capturing SSL errors
Working with REST
Invoke-RestMethod
Simple requests
Requests with arguments
Working with paging
Working with authentication
Using basic authentication
OAuth
Creating an application
Getting an authorization code
OAuth browser issues
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
Chapter 14: Remoting and Remote Management
Technical requirements
WS-Management
Enabling remoting
Get-WSManInstance
The WSMan drive
Remoting and SSL
Set-WSManQuickConfig
Remoting and permissions
Remoting permissions GUI
Remoting permissions by script
User Account Control
Trusted hosts
PSSessions
New-PSSession
Get-PSSession
Invoke-Command
Local functions and remote sessions
Using splatting with ArgumentList
The AsJob parameter
Disconnected sessions
The using variable scope
The Enter-PSSession command
Import-PSSession
Export-PSSession
Copying items between sessions
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
New-CimSession
Get-CimSession
Using CIM sessions
Just Enough Administration
Session configuration
Role capabilities
Summary
Chapter 15: Asynchronous Processing
Working with jobs
The Start-Job, Get-Job, and Remove-Job commands
The Receive-Job command
The Wait-Job command
Jobs and the using scope modifier
The background operator
The ThreadJob module
Batching jobs
Reacting to events
The Register-ObjectEvent and *-Event commands
The Get-EventSubscriber and Unregister-Event commands
The Action, Event, EventArgs, and MessageData parameters
Using runspaces and runspace pools
Creating a PowerShell instance
The Invoke and BeginInvoke methods
The EndInvoke method and the PSDataCollection object
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 Runspace-synchronized objects
Summary
Chapter 16: 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 elements
Handling events
Buttons and the Click event
ComboBox and SelectionChanged
Adding elements programmatically
Sorting a ListView
Responsive interfaces
Import-Xaml and Runspace support
Using the Dispatcher
Summary
Chapter 17: Scripts, Functions, and Script Blocks
About style
Capabilities of scripts, functions, and script blocks
Scripts and using statements
Scripts and Requires
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 cleanup
begin
process
end
cleanup
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 operator to break up lines
Comment-based help
Parameter help
Examples
Summary
Chapter 18: 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 ValidateCount attribute
The ValidateDrive attribute
The ValidateUserDrive attribute
The ValidateLength attribute
The ValidatePattern attribute
The ValidateRange attribute
The ValidateScript attribute
The ValidateSet 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
Using PSTypeName
About ValueFromPipelineByPropertyName
ValueFromPipelineByPropertyName and parameter aliases
Defining parameter sets
Argument completers
The ArgumentCompleter attribute
Using Register-ArgumentCompleter
Listing registered argument completers
Dynamic parameters
Creating a RuntimeDefinedParameter object
Using RuntimeDefinedParameterDictionary
Using dynamic parameters
Conditional parameters
Summary
Chapter 19: 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 for parameters
Argument-transformation attribute classes
Validation attribute classes
ValidateArgumentsAttribute
ValidateEnumeratedArgumentsAttribute
Classes for ValidateSet
Classes and DSC
Implementing Get
Implementing Set
Implementing Test
Using the resource
Summary
Chapter 20: Building Modules
Technical requirements
Creating a module
The root module
Export-ModuleMember
Module manifests
Test-ModuleManifest
Update-ModuleManifest
Publishing a module
Publishing and side-by-side versioning
Multi-file module layout
Dot sourcing module content
Merging module content
ModuleBuilder and DSC resources
Module scope
Accessing module scope
Modules, classes, and enumerations
Initializing and removing modules
The ScriptsToProcess property
The OnRemove event
Summary
Chapter 21: 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 TestCases parameter
Using the ForEach parameter
Conditional testing
Using Set-ItResult
Using Skip
Pester phases
Before and After blocks
Mocking commands
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
Chapter 22: Error Handling
Error types
Non-terminating errors
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
Nesting try, catch, and finally
About trap
Using trap
trap, scope, and continue
Summary
Chapter 23: Debugging and Troubleshooting
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 the CALL STACK
Using launch configurations
Using WATCH
Summary
Packt Page
Other Books You May Enjoy
Index