<p><span>Use PowerShell to save time and reduce the potential for human error by writing scripts that automate the execution of tasks</span></p><p><span>Purchase of the print or Kindle book includes a free PDF eBook.</span></p><p><span><br></span></p><p><span>Key Features: </span></p><ol></ol><span>
Mastering PowerShell Scripting - Fifth Edition: Automate repetitive tasks and simplify complex administrative tasks using PowerShell
โ Scribed by Chris Dent
- Publisher
- Packt Publishing
- Year
- 2024
- Tongue
- English
- Leaves
- 827
- Edition
- 5
- Category
- Library
No coin nor oath required. For personal study only.
โฆ Synopsis
Use PowerShell to save time and reduce the potential for human error by writing scripts that automate the execution of tasks
Purchase of the print or Kindle book includes a free PDF eBook.
Key Features:
Explores PowerShell as a programming languageTake advantage of the features built into the PowerShell language in day-to-day automationAutomation of complex tasks, data manipulation, and environment security
Book Description:
Mastering PowerShell Scripting, Fifth Edition, can help you overcome any fears and become proficient in navigating PowerShell's capabilities. This edition includes new chapters on debugging, troubleshooting, and creating GUIs. You will learn about the latest features of PowerShell 7.3, including working with parameters, objects, and .NET classes. The book covers basic and advanced topics, such as asynchronous processing, desired state configuration, managing large amounts of data, interacting with other services, and working with regular expressions and Windows Management Instrument (WMI). Discover how to efficiently use PowerShell's automation features and error-handling techniques for more complex scripts and filters.
Starting with foundational knowledge, this extensive guide progresses to advanced concepts like using complex scripts and filters, asynchronous processing, desired state configuration, debugging, and error-handling techniques. You will learn how to effectively handle large data sets and interact with external services using PowerShell 7.3. Additionally, you'll discover how to fully utilize PowerShell's automation capabilities, including parsing data, manipulating regular expressions, and working with WMI using various methods.
What You Will Learn:
Create scripts that can be run on different systemsPowerShell is highly extensible and can integrate with other programming languagesDiscover the powerful command-line interface that enables users to perform various operations with easeCreate reusable scripts and functions in PowerShellUtilize PowerShell for various purposes, including system administration, automation, and data processingIntegrate PowerShell with other technologies such as .NET, COM, and WMIWork with common data formats such as XML, JSON, and CSV in PowerShellCreate custom PowerShell modules and cmdlets to extend its functionality
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
Cover
Copyright
Contributors
Table of Contents
Preface
Chapter 1: 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
Chapter 2: 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
Chapter 3: 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
Chapter 4: 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
Chapter 5: 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
Chapter 6: 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
Chapter 7: 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
Chapter 10: 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
Chapter 11: 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
Chapter 12: 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
Chapter 13: 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
Chapter 14: 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
Chapter 15: 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
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 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
Chapter 17: 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
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 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
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 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
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 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
Chapter 22: 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
Chapter 23: 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
PacktPage
Other Books You May Enjoy
Index
๐ SIMILAR VOLUMES
<p><span>Use PowerShell to save time and reduce the potential for human error by writing scripts that automate the execution of tasks</span></p><p><span>Purchase of the print or Kindle book includes a free PDF eBook.</span></p><p><span>Key Features</span></p><p><span>- Explores PowerShell as a progr
<p><span>Use PowerShell to save time and reduce the potential for human error by writing scripts that automate the execution of tasks</span></p><p><span>Purchase of the print or Kindle book includes a free PDF eBook.</span></p><p><span>Key Features</span></p><p><span>- Explores PowerShell as a progr
"Comma"--"Format" -- "Increment and decrement" -- "Join" -- "Summary" -- "Chapter 6: Variables, Arrays, and Hashtables " -- "Naming and creating variables" -- "Variable commands" -- "Clear-Variable" -- "Get-Variable" -- "New-Variable" -- "Remove-Variable" -- "Set-Variable" -- "Variable scope" -- "Lo
Master the art of automating and managing your environment using PowerShell About This Book Find quick solutions to automate your environment with ease Work with large amounts of data effortlessly with PowerShell data types and secure them Packed with real-world examples to automate and simplify the