𝔖 Scriptorium
✦   LIBER   ✦

πŸ“

Mastering PowerShell Scripting

✍ Scribed by Chris Dent


Publisher
Packt Publishing
Year
2024
Tongue
English
Edition
5
Category
Library

⬇  Acquire This Volume

No coin nor oath required. For personal study only.

✦ Synopsis


PowerShell scripts provides a convenient method for automating tasks, using them proficiently can be challenging. This all-inclusive guide begins at the basics and covers advanced concepts, equipping you with tips to become an expert in PowerShell Core 7.3 scripting.

✦ Table of 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
Strings, Numbers, and Dates (Online Chapter)
Regular Expressions (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
Building Modules (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


πŸ“œ SIMILAR VOLUMES


Mastering Windows PowerShell Scripting
✍ Blawat B.J.W. πŸ“‚ Library 🌐 English

Packt Publishing, 2015. β€” 220 p. β€” ISBN: 1782173552, ISBN-13: 978-1-78217-355-7.<br/>На Π°Π½Π³Π». языкС.<br/> <br/>PowerShell is quickly becoming the de facto standard for scripting in Microsoft Windows environments. It enables the automation of otherwise complex tasks, providing interactivity between d

Mastering PowerShell Scripting for SysAd
✍ Anthony Wanger πŸ“‚ Library πŸ“… 2024 πŸ› Independently Published 🌐 English

Mastering PowerShell Scripting for SysAdmins: Automate Complex Tasks with Confidence PowerShell, the versatile scripting language built for Windows systems, is your key to conquering tedious tasks and streamlining sysadmin work. This book delves deep into its capabilities, empowering you to autom