Preface What this book covers What you need for this book Who this book is for Conventions Reader feedback Customer support Downloading the color images of this book Errata Piracy Questions Introduction to PowerShell What is PowerShell? Quick reference Comments Special characters Tick in PowerShell Common operators Dropping unwanted output Creating arrays and hashtables Strings Common reserved variables Quick commands and hot keys PowerShell editors PowerShell ISE Features Installing ISE Preview Starting ISE Visual Studio Code Features Console Version control (Git) PowerShell on Linux Installing PowerShell Where are the PowerShell files? Changing the shell Profiles Multiplatform scripting Line endings File encoding Path separator Example Summary Working with PowerShell 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 Parameters and parameter sets Parameters Optional parameters Optional positional parameters Mandatory parameters Mandatory positional parameters Switch parameters Common parameters Parameter values Parameter sets Confirm, WhatIf, and Force Confirm parameter ConfirmPreference WhatIf parameter WhatIfPreference Force parameter Providers Drives using providers Using providers Summary Modules and Snap-Ins What is a module? What is the PowerShell Gallery? The Get-Module command The Import-Module command The Remove-Module command The Find-Module command The Install-Module command The Save-Module command What is a snap-in? Using snap-ins Summary Working with Objects in PowerShell Pipelines Standard output Non-standard output The object pipeline Members The Get-Member command Accessing properties Using methods Access modifiers The Add-Member command Enumerating and filtering The ForEach-Object command Where-Object command Selecting and sorting The Select-Object command The Sort-Object command 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 Summary Operators Arithmetic operators Operator precedence Addition and subtraction operators Multiplication, division, and modulus operators Shift left and shift right operators Assignment operators Assign, add and assign, and subtract and assign Multiply and assign, divide and assign, and modulus and assign Comparison operators Case-sensitivity Comparison operators and arrays Equal to and not equal to Like and not like Greater than and less than Contains and in Regular-expression-based operators Match and not match Replace Split Binary operators Binary and Binary or Binary exclusive or Binary not Logical operators And Or Exclusive or Not Type operators As Is and isnot Redirection operators Redirection to a file Redirecting streams to standard output Redirection to null Other operators Call Comma Format Increment and decrement Join Summary Variables, Arrays, and Hashtables Naming and creating variables Variable commands Clear-Variable Get-Variable New-Variable Remove-Variable Set-Variable Variable scope Local and Global scope Private scope Script scope Type and type conversion Objects assigned to variables Arrays Creating an array Arrays with a type Adding elements to an array Selecting elements from an array Changing element values in an array Removing elements from an array Removing elements by index Removing elements by value Clearing an array Filling variables from arrays Multi-dimensional and jagged arrays Hashtables Creating a hashtable Adding and changing elements to a hashtable Selecting elements from a hashtable Enumerating a hashtable Removing elements from a hashtable Lists, dictionaries, queues, and stacks Lists Creating a list Adding elements to the list Selecting elements from the list Removing elements from the list Changing element values in a list Dictionaries Creating a dictionary Adding and changing elements in a dictionary Selecting elements from a dictionary Enumerating a dictionary Removing elements from a dictionary Queues Creating a queue Enumerating the queue Adding elements to the queue Removing elements from the queue Stacks Creating a stack Enumerating the stack Adding elements to the stack Removing elements from the stack Summary Branching and Looping Conditional statements If, else, and elseif Assignment within if statements Switch Wildcard and Regex Expressions Loops Foreach For Do until and do while While Break and continue Summary Working with .NET Assemblies Namespaces Types Classes Constructors Calling constructors Calling constructors with lists of arguments Arguments as an array Properties and methods Static properties Static methods Non-public classes Type accelerators Using Using assemblies Using namespaces Summary Data Parsing and Manipulation String manipulation Indexing into strings String methods and arrays Substring Split Replace Trim, TrimStart, and TrimEnd Insert and Remove IndexOf and LastIndexOf PadLeft and PadRight ToUpper, ToLower, and ToTitleCase Contains, StartsWith, and EndsWith Chaining methods Converting strings Working with Base64 How Base64 works Working with CSV Convert-String ConvertFrom-String Number manipulation Large byte values Power-of-10 Hexadecimal Using System.Math Converting strings to numeric values Date and time manipulation DateTime parameters Parsing dates Changing dates Comparing dates Summary Regular Expressions Regex basics Debugging regular expressions Literal characters Any character (.) Repetition with * and + The escape character () Optional characters Non-printable characters Anchors Repetition Exploring the quantifiers Character classes Ranges Negated character class Character class subtraction Shorthand character classes Alternation Grouping Repeating groups Restricting alternation Capturing values Named capture groups Non-capturing groups Examples of regular expressions MAC addresses IP addresses Netstat command Summary Files, Folders, and the Registry Working with providers Navigating Getting items Drives Items Testing existence Creating and deleting items Invoking items Item properties Filesystem properties Adding and removing file attributes Registry values Permissions Ownership Access and audit Rule protection Inheritance and propagation flags Removing access control entries Copying lists and entries Adding access control entries Filesystem rights Registry rights Transactions File catalogs New-FileCatalog Test-FileCatalog Summary Windows Management Instrumentation Working with WMI WMI classes WMI commands The WMI Query Language Understanding SELECT, WHERE, and FROM Escape sequences and wildcard characters Logic operators Comparison operators Quoting values Associated classes WMI object path Using ASSOCIATORS OF CIM cmdlets Getting instances Getting classes Calling methods Creating instances Working with CIM sessions Associated classes The WMI cmdlets 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 HTML, XML, and JSON HTML ConvertTo-Html Multiple tables Adding style HTML and special characters XML Elements and attributes Namespaces Schemas System.Xml ConvertTo-Xml XML type accelerator XPath and Select-Xml Working with namespaces Creating documents Modifying element and attribute values Adding elements Copying nodes between documents Removing elements and attributes Schema validation 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 ConvertFrom-Json Summary Working with REST and SOAP Web requests HTTP methods HTTPS Bypassing SSL errors Capturing SSL errors Working with REST Invoke-RestMethod Simple requests Requests with arguments Working with authentication Walking through OAuth Creating an application Getting an authorization code Requesting an access token Getting a list of playlists Getting a list of tracks Working with SOAP New-WebServiceProxy Methods Types Namespaces Summary Remoting and Remote Management WS-Management Enabling remoting Get-WSManInstance WSMan drive Remoting and SSL Set-WSManQuickConfig Remoting and permissions Remoting permissions GUI Remoting permissions by script User Account Control Trusted hosts CIM sessions New-CimSession Get-CimSession Using CIM sessions PS sessions New-PSSession Get-PSSession Invoke-Command Local functions and remote sessions Using splatting with ArgumentList The AsJob parameter Disconnected sessions The using variable scope Enter-PSSession Import-PSSession Export-PSSession Copying items between sessions The double-hop problem CredSSP Passing credentials Summary Testing Static analysis Abstract syntax tree PSScriptAnalyzer Suppressing rules Testing with Pester Why write tests? What to test Describe and It Test cases Independent verification Assertions Be BeIn BeLessThan BeLike BeLikeExactly BeNullOrEmpty BeOfType FileContentMatch FileContentMatchExactly FileContentMatchMultiline Exist Match MatchExactly Throw Not Context Before and After TestDrive Mock Assert-MockCalled Parameter filtering Mocking objects Fabricating objects Mocking methods CIM objects Pester in practice Summary Error Handling Error types Terminating errors Non-terminating errors Error action Raising errors Error records Write-Error Throw and ThrowTerminatingError Error and ErrorVariable Catching errors Try, catch, and finally Try Catch Finally Rethrowing errors Inconsistent error behavior Throw and ErrorAction Nesting try-catch-finally Terminating or non-terminating Trap Using trap Trap, scope, and continue Summary