0%

Book Description

Grasp advanced PowerShell Core 6.0 functionalities to automate your environment

Key Features

  • Keep up with changes introduced in PowerShell Core 6.0
  • Easily maintain appropriate compatibility with older versions
  • Automate complex tasks, manipulate data, and secure your environment with PowerShell Core 6.0

Book Description

PowerShell scripts offer a handy way to automate various chores, however working effectively with these scripts can be a difficult task.

This comprehensive guide starts with the fundamentals before moving on to advanced-level topics to help you become a PowerShell Core 6.0 expert. The first module, PowerShell Core 6.0 Fundamentals, begins with the new features of PowerShell Core 6.0, installing it on Linux, and working with parameters, objects and .NET classes from within PowerShell Core 6.0. As you make your way through the chapters, you'll see how to efficiently manage large amounts of data and interact with other services using PowerShell Core 6.0. You'll be able to make the most of PowerShell Core 6.0's powerful automation feature, where you will have different methods available to parse data and manipulate regular expressions and Windows Management Instrumentation (WMI). After having explored automation, you will enter the extending PowerShell Core 6.0 module, covering asynchronous processing and desired state configuration. In the last module, you will learn to extend PowerShell Core 6.0 using advanced scripts and filters, and also debug issues along with working on error handling techniques.

By the end of this book, you will be an expert in scripting with PowerShell Core 6.0.

What you will learn

  • Optimize code through the use of functions, switches, and looping structures
  • Work with objects and operators to test and manipulate data
  • Parse and manipulate different data types
  • Create scripts and functions using PowerShell
  • Use jobs, events, and popular public modules which assist with implementing multithreading
  • Write .NET classes with ease within the 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

If you are a system administrator who wants to become an expert in controlling and automating your Windows environment, then Mastering Windows PowerShell Scripting is for you. It is also ideal for those new to the PowerShell language.

Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Windows PowerShell Scripting Third Edition
  3. About Packt
    1. Why subscribe?
    2. Packt.com
  4. Contributors
    1. About the author
    2. About the reviewers
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Section 1: Exploring PowerShell Fundamentals
  7. Introduction to PowerShell
    1. Technical requirements
    2. What is PowerShell?
    3. PowerShell editors
    4. 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
    5. Command naming and discovery
      1. Verbs
      2. Nouns
      3. Finding commands
      4. Aliases
    6. Parameters and parameter sets
      1. Parameters
        1. Optional parameters
        2. Optional positional parameters
        3. Mandatory parameters
        4. Mandatory positional parameters
        5. Switch parameters
        6. Common parameters
      2. Parameter values
      3. Parameter sets
      4. Confirm, WhatIf, and Force
        1. Confirm parameter
        2. ConfirmPreference
        3. WhatIf parameter
        4. WhatIfPreference
        5. Force parameter
    7. Introduction to providers
      1. Drives using providers
      2. Using providers
    8. Introduction to splatting
      1. Splatting to avoid escaped end-of-line
      2. Splatting to avoid repetition
      3. Splatting and positional parameters
    9. Summary
  8. Modules and Snap-ins
    1. Introducing modules
      1. What is the PowerShell Gallery?
      2. The Get-Module command
        1. PSModulePath in Windows PowerShell
        2. PSModulePath in PowerShell Core
        3. Get-Module, PSCompatibility, and PSEdition
      3. The Import-Module command
      4. The Remove-Module command
      5. The Find-Module command
      6. The Install-Module command
      7. The Update-Module command
      8. The Save-Module command
    2. PowerShell Core and the WindowsCompatibility module
      1. The compatibility session
      2. Add-WindowsPSModulePath
      3. Get-WinModule and Import-WinModule
      4. Copy-WinModule
      5. Invoke-WinCommand
    3. Introducing snap-ins
      1. Using snap-ins
    4. Summary
  9. 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 properties
      3. Using methods
      4. Access modifiers
      5. The Add-Member command
    3. Enumerating and filtering
      1. The ForEach-Object command
      2. Where-Object command
    4. Selecting and sorting
      1. The Select-Object command
      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
    8. Summary
  10. Operators
    1. Arithmetic operators
      1. Operator precedence
      2. Addition and subtraction operators
        1. Addition operators
        2. Subtraction operator
      3. Multiplication, division, and remainder operators
        1. Multiplication operator
        2. Division operator
        3. Remainder operator
      4. Shift left and shift right operators
    2. Assignment operators
      1. Assign, add and assign, and subtract and assign
      2. Multiply and assign, divide and assign, and modulus and assign
    3. Comparison operators
      1. Case-sensitivity
      2. Comparison operators and arrays
      3. Equal to and not equal to
      4. Like and not like
      5. Greater than and less than
      6. Contains and in
    4. Regular expression-based operators
      1. Match and not match
      2. Replace
      3. Split
    5. Binary operators
      1. Binary and
      2. Binary or
      3. Binary exclusive or
      4. Binary not
    6. Logical operators
      1. And
      2. Or
      3. Exclusive or
      4. Not
    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
    10. Summary
  11. Section 2: Working with Data
  12. Variables, Arrays, and Hashtables
    1. Naming and creating variables
    2. Variable commands
      1. Clear
      2. Get
      3. New
      4. Remove
      5. Set
    3. Variable provider
    4. Variable scope
      1. Local and global scope
      2. Private scope
      3. Script scope
    5. Type and type conversion
    6. Objects assigned to variables
    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 from an array
        1. Removing elements by index
        2. Removing elements by value
        3. Clearing an array
      7. Filling variables from arrays
      8. Multi-dimensional and jagged arrays
    8. Hashtables
      1. Creating a hashtable
      2. Adding and changing elements to a hashtable
      3. Selecting elements from a hashtable
      4. Enumerating a hashtable
      5. Removing elements from a hashtable
    9. Lists, dictionaries, queues, and stacks
      1. Lists
        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. Dictionaries
        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. Queues
        1. Creating a queue
        2. Enumerating the queue
        3. Adding elements to the queue
        4. Removing elements from the queue
      4. Stacks
        1. Creating a stack
        2. Enumerating the stack
        3. Adding elements to the stack
        4. Removing elements from the stack
    10. Summary
  13. Branching and Looping
    1. Conditional statements
      1. if, else, and elseif
        1. Assignment within if statements
      2. switch
        1. wildcard and regex
        2. Expressions
    2. Loops
      1. foreach
      2. for
      3. do until and do while
      4. while
      5. break and continue
    3. Branching and assignment
    4. Summary
  14. Working with .NET
    1. Assemblies
    2. Namespaces
    3. Types
    4. Classes
    5. Constructors
      1. Calling constructors
      2. Calling constructors with lists of arguments
      3. Arguments as an array
      4. Creating objects from hashtables
    6. Properties and methods
    7. Static properties
    8. Static methods
    9. Non-public classes
    10. Type accelerators
    11. The using keyword
      1. Using assemblies
      2. Using namespaces
    12. Summary
  15. Strings, Numbers, and Dates
    1. Manipulating strings
      1. Indexing into strings
      2. String methods and arrays
      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. Chaining methods
    2. Converting strings
      1. Working with Base64
      2. Working with comma-separated value strings
      3. Convert-String
      4. ConvertFrom-String
    3. Manipulating numbers
      1. Large byte values
      2. Power of 10
      3. Hexadecimal
      4. Using System.Math
    4. Converting strings into numeric values
    5. Manipulating dates and times
      1. DateTime parameters
      2. Parsing dates
      3. Changing dates
      4. Comparing dates
    6. Summary
  16. Regular Expressions
    1. Regex basics
      1. Debugging regular expressions
      2. Literal characters
      3. Any character (.)
      4. Repetition with * and +
      5. The escape character ()
      6. Optional characters
      7. Non-printable characters
    2. Anchors
    3. Repetition
      1. Exploring the quantifiers
    4. Character classes
      1. Ranges
      2. Negated character class
      3. Character class subtraction
      4. Shorthand character classes
    5. Alternation
    6. Grouping
      1. Repeating groups
      2. Restricting alternation
      3. Capturing values
      4. Named capture groups
      5. Non-capturing groups
    7. Examples of regular expressions
      1. MAC addresses
      2. IP addresses
      3. The netstat command
      4. Formatting certificates
    8. Summary
  17. Files, Folders, and the Registry
    1. Working with providers
      1. Navigating
      2. Getting items
      3. Drives
    2. Items
      1. Testing for existing items
      2. Creating and deleting items
      3. Invoking items
    3. Item properties
      1. Filesystem properties
      2. Adding and removing file attributes
      3. Registry values
    4. Windows permissions
      1. Ownership
      2. Access and audit
      3. Rule protection
      4. Inheritance and propagation flags
      5. Removing access control entries
      6. Copying lists and entries
      7. Adding access control entries
        1. Filesystem rights
        2. Registry rights
        3. Numeric values in the access control list
    5. Transactions
    6. File catalogs
      1. New-FileCatalog
      2. Test-FileCatalog
    7. Summary
  18. Windows Management Instrumentation
    1. Working with WMI
      1. WMI classes
      2. WMI commands
      3. The WMI Query Language
        1. Understanding SELECT, WHERE, and FROM
        2. Escape sequences and wildcard characters
        3. Logic operators
        4. Comparison operators
        5. Quoting values
      4. Associated classes
        1. WMI object paths
        2. Using ASSOCIATORS OF
    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 cmdlets
      1. Getting instances
      2. Working with dates
      3. Getting classes
      4. Calling methods
      5. Creating instances
      6. Associated classes
    4. 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
    5. Summary
  19. HTML, XML, and JSON
    1. HTML
      1. ConvertTo-Html
      2. Multiple tables
      3. Adding style
      4. HTML and special characters
    2. XML
      1. Elements and attributes
      2. Namespaces
      3. Schemas
    3. System.Xml
      1. ConvertTo-Xml
      2. XML type accelerator
      3. XPath and Select-Xml
      4. Working with namespaces
      5. Creating documents
      6. Modifying element and attribute values
      7. Adding elements
      8. Copying nodes between documents
      9. Removing elements and attributes
      10. Schema validation
    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
      2. ConvertFrom-Json
    6. Summary
  20. 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
        1. Using basic authentication
        2. OAuth
        3. Creating an application
        4. Getting an authorization code
        5. Requesting an access token
        6. Using a token
    4. Working with SOAP
      1. Finding a SOAP service
      2. New-WebServiceProxy
      3. Methods
      4. Methods and enumerations
      5. Methods and SOAP objects
      6. Overlapping services
    5. Summary
  21. Section 3: Automating with PowerShell
  22. 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. Summary
  23. 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
    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
  24. Section 4: Extending PowerShell
  25. Scripts, Functions, and Filters
    1. Introducing scripts, functions, and filters
      1. Scripts and Requires
      2. Scripts and using statements
      3. Nesting functions
      4. Comment-based help
        1. Parameter help
        2. Examples
      5. Working with long lines
        1. Line break after pipe
        2. Line break after an operator
        3. Using the array operator to break up lines
    2. Begin, process, and end
      1. Begin
      2. Process
      3. End
      4. Named blocks and return
      5. Leaky functions
        1. The Out-Null command
        2. Assigning to null
        3. Redirecting to null
        4. Casting to Void
    3. Param, parameters, and CmdletBinding
      1. Parameter types
        1. Nullable types
      2. Default values
      3. Cross-referencing parameters
      4. The CmdletBinding attribute
        1. Common parameters
        2. CmdletBinding properties
    4. ShouldProcess and ShouldContinue
      1. ShouldProcess
      2. ShouldContinue
    5. Summary
  26. 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 ValidateLength attribute
        6. The ValidatePattern attribute
        7. The ValidateRange attribute
        8. The ValidateScript attribute
        9. 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
        1. Accepting null input
        2. Input object types
        3. Using ValueFromPipeline for multiple parameters
        4. Using PSTypeName
      2. About ValueFromPipelineByPropertyName
        1. ValueFromPipelineByPropertyName and parameter aliases
    4. Defining parameter sets
    5. Argument-completers
      1. The argument-completer attribute
      2. Using Register-ArgumentCompleter
      3. Listing registered argument-completers
    6. Dynamic parameters
      1. Creating a RuntimeDefinedParameter object
      2. Using the RuntimeDefinedParameterDictionary
      3. Using dynamic parameters
      4. Conditional parameters
    7. Summary
  27. 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 values
    2. Creating a class
      1. Properties
      2. Constructors
      3. Methods
      4. Inheritance
        1. Constructor inheritance
        2. Chaining constructors
      5. The Hidden modifier
      6. The Static modifier
    3. Argument-transformation attribute classes
    4. Validation attribute classes
      1. ValidateArgumentsAttribute
      2. ValidateEnumeratedArgumentsAttribute
    5. Classes and DSC
      1. Implementing Get
      2. Implementing Set
      3. Implementing Test
      4. Using the resource
    6. Summary
  28. Building Modules
    1. Technical requirements
    2. Module layout
      1. The root module
      2. The Export-ModuleMember command
      3. Module manifest
      4. Export-ModuleMember or FunctionsToExport
      5. Side-by-side versioning
      6. Dependencies
    3. Multi-file module layout
      1. Dot-sourcing module content
      2. Merging module content
    4. Module scope
      1. Accessing module scope
    5. Initializing and removing modules
      1. The ScriptsToProcess key
      2. The OnRemove event
    6. Summary
  29. Testing
    1. Technical requirement
    2. Static analysis
      1. AST
      2. Tokenizer
      3. PSScriptAnalyzer
      4. Suppressing rules
      5. Custom script analyzer rules
        1. Creating a custom rule
        2. AST-based rules
        3. Token-based rules
        4. Using custom rules
    3. Testing with Pester
      1. Why write tests?
      2. What to test
      3. Describe and It
      4. Test cases
      5. Independent verification
      6. Assertions
        1. Testing for errors
      7. Context
      8. Before and after
      9. TestDrive
      10. Mock
        1. Assert-MockCalled
        2. Parameter filtering
        3. Mocking non-local commands
      11. Mocking objects
        1. Fabricating objects
        2. Mocking existing members
        3. Using New-MockObject
        4. Mocking CIM objects
      12. Pester in practice
    4. Summary
  30. Error Handling
    1. Error types
      1. Terminating errors
      2. Non-terminating errors
    2. Error actions
    3. Raising errors
      1. Error records
      2. Write-Error
      3. throw and ThrowTerminatingError
      4. Error and ErrorVariable
    4. Catching errors
      1. try, catch, and finally
        1. try
        2. catch
        3. finally
      2. Re-throwing errors
      3. Inconsistent error behavior
      4. throw and ErrorAction
      5. Nesting try-catch-finally
      6. Terminating or non-terminating
      7. trap
        1. Using trap
        2. trap, scope, and continue
    5. Summary
  31. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think
3.235.249.219