0%

Grasp advanced PowerShell 7.1 functionalities for effective automation of your environment

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, although working effectively with these scripts can be challenging. Mastering PowerShell Scripting helps you to 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. Some familiarity with operating systems would be useful, but not essential.

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