Mastering Windows PowerShell Scripting - Second Edition

Book description

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 management of your Windows environment

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 this book is for you. It is also for those new to the PowerShell language.

What You Will Learn

  • Optimize code through the use of functions, switches, and looping structures
  • Install PowerShell on your Linux system
  • Utilize variables, hashes, and arrays to store data
  • Work with Objects and Operators to test and manipulate data
  • Parse and manipulate different data types
  • Write .NET classes with ease within the PowerShell
  • Create and implement regular expressions in PowerShell scripts
  • Deploy applications and code with PowerShell's Package management modules
  • Leverage session-based remote management
  • Manage files, folders, and registries through the use of PowerShell

In Detail

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

This comprehensive guide starts from scratch and covers advanced-level topics to make you a PowerShell expert. The first module, PowerShell Fundamentals, begins with new features, installing PowerShell on Linux, working with parameters and objects, and also how you can work with .NET classes from within PowerShell.

In the next module, you'll see how to efficiently manage large amounts of data and interact with other services using PowerShell. You'll be able to make the most of PowerShell's powerful automation feature, where you will have different methods to parse and manipulate data, regular expressions, and WMI.

After automation, you will enter the Extending PowerShell module, which covers topics such as asynchronous processing and, creating modules. The final step is to secure your PowerShell, so you will land in the last module, Securing and Debugging PowerShell, which covers PowerShell execution policies, error handling techniques, and testing.

By the end of the book, you will be an expert in using the PowerShell language.

Style and approach

This practical guide covers all the advanced PowerShell functionalities that an administrator needs to learn to automate their environments.

Table of contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the color images of this book
      2. Errata
      3. Piracy
      4. Questions
  2. Introduction to PowerShell
    1. What is PowerShell?
    2. Quick reference
      1. Comments
      2. Special characters
        1. Tick in PowerShell
      3. Common operators
      4. Dropping unwanted output
      5. Creating arrays and hashtables
      6. Strings
      7. Common reserved variables
      8. Quick commands and hot keys
    3. PowerShell editors
      1. PowerShell ISE
        1. Features
        2. Installing ISE Preview
        3. Starting ISE
      2. Visual Studio Code
        1. Features
        2. Console
        3. Version control (Git)
    4. PowerShell on Linux
      1. Installing PowerShell
      2. Where are the PowerShell files?
      3. Changing the shell
      4. Profiles
      5. Multiplatform scripting
        1. Line endings
        2. File encoding
        3. Path separator
        4. Example
    5. Summary
  3. Working with PowerShell
    1. 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
    2. Command naming and discovery
      1. Verbs
      2. Nouns
      3. Finding commands
      4. Aliases
    3. 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
    4. Providers
      1. Drives using providers
      2. Using providers
    5. Summary
  4. Modules and Snap-Ins
    1. What is a module?
    2. What is the PowerShell Gallery?
    3. The Get-Module command
    4. The Import-Module command
    5. The Remove-Module command
    6. The Find-Module command
    7. The Install-Module command
    8. The Save-Module command
    9. What is a snap-in?
    10. Using snap-ins
    11. Summary
  5. 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
  6. Operators
    1. Arithmetic operators
      1. Operator precedence
      2. Addition and subtraction operators
      3. Multiplication, division, and modulus operators
      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
  7. Variables, Arrays, and Hashtables
    1. Naming and creating variables
    2. Variable commands
      1. Clear-Variable
      2. Get-Variable
      3. New-Variable
      4. Remove-Variable
      5. Set-Variable
    3. Variable scope
      1. Local and Global scope
      2. Private scope
      3. Script scope
    4. Type and type conversion
    5. Objects assigned to variables
    6. 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
    7. 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
    8. 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
    9. Summary
  8. 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. Summary
  9. 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
    6. Properties and methods
    7. Static properties
    8. Static methods
    9. Non-public classes
    10. Type accelerators
    11. Using
      1. Using assemblies
      2. Using namespaces
    12. Summary
  10. Data Parsing and Manipulation
    1. String manipulation
      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
        1. How Base64 works
      2. Working with CSV
      3. Convert-String
      4. ConvertFrom-String
    3. Number manipulation
      1. Large byte values
      2. Power-of-10
      3. Hexadecimal
      4. Using System.Math
    4. Converting strings to numeric values
    5. Date and time manipulation
      1. DateTime parameters
      2. Parsing dates
      3. Changing dates
      4. Comparing dates
    6. Summary
  11. 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. Netstat command
    8. Summary
  12. Files, Folders, and the Registry
    1. Working with providers
      1. Navigating
      2. Getting items
      3. Drives
    2. Items
      1. Testing existence
      2. Creating and deleting items
      3. Invoking items
    3. Item properties
      1. Filesystem properties
      2. Adding and removing file attributes
      3. Registry values
    4. 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
    5. Transactions
    6. File catalogs
      1. New-FileCatalog
      2. Test-FileCatalog
    7. Summary
  13. 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 path
        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
  14. 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
  15. Working with REST and SOAP
    1. Web requests
      1. HTTP methods
      2. HTTPS
      3. Bypassing SSL errors
      4. Capturing SSL errors
    2. Working with REST
      1. Invoke-RestMethod
      2. Simple requests
      3. Requests with arguments
      4. Working with authentication
      5. Walking through OAuth
        1. Creating an application
        2. Getting an authorization code
        3. Requesting an access token
        4. Getting a list of playlists
        5. Getting a list of tracks
    3. Working with SOAP
      1. New-WebServiceProxy
      2. Methods
      3. Types
      4. Namespaces
    4. Summary
  16. Remoting and Remote Management
    1. WS-Management
      1. Enabling remoting
      2. Get-WSManInstance
      3. 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
    2. CIM sessions
      1. New-CimSession
      2. Get-CimSession
      3. Using CIM sessions
    3. PS sessions
      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. Enter-PSSession
      5. Import-PSSession
      6. Export-PSSession
      7. Copying items between sessions
    4. The double-hop problem
      1. CredSSP
      2. Passing credentials
    5. Summary
  17. Testing
    1. Static analysis
      1. Abstract syntax tree
      2. PSScriptAnalyzer
      3. Suppressing rules
    2. Testing with Pester
      1. Why write tests?
      2. What to test
      3. Describe and It
      4. Test cases
      5. Independent verification
      6. Assertions
        1. Be
        2. BeIn
        3. BeLessThan
        4. BeLike
        5. BeLikeExactly
        6. BeNullOrEmpty
        7. BeOfType
        8. FileContentMatch
        9. FileContentMatchExactly
        10. FileContentMatchMultiline
        11. Exist
        12. Match
        13. MatchExactly
        14. Throw
        15. Not
      7. Context
      8. Before and After
      9. TestDrive
      10. Mock
        1. Assert-MockCalled
        2. Parameter filtering
      11. Mocking objects
        1. Fabricating objects
        2. Mocking methods
        3. CIM objects
      12. Pester in practice
    3. Summary
  18. Error Handling
    1. Error types
      1. Terminating errors
      2. Non-terminating errors
    2. Error action
    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. Rethrowing 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

Product information

  • Title: Mastering Windows PowerShell Scripting - Second Edition
  • Author(s): Chris Dent, Brenton J.W. Blawat
  • Release date: October 2017
  • Publisher(s): Packt Publishing
  • ISBN: 9781787126305