Title Page Copyright and Credits Mastering Windows PowerShell Scripting Third Edition About Packt Why subscribe? Packt.com Contributors About the author About the reviewers Packt is searching for authors like you Preface Who this book is for What this book covers To get the most out of this book Download the example code files Download the color images Conventions used Get in touch Reviews Section 1: Exploring PowerShell Fundamentals Introduction to PowerShell Technical requirements What is PowerShell? 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 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 Introduction to providers Drives using providers Using providers Introduction to splatting Splatting to avoid escaped end-of-line Splatting to avoid repetition Splatting and positional parameters Summary Modules and Snap-ins Introducing modules What is the PowerShell Gallery? The Get-Module command PSModulePath in Windows PowerShell PSModulePath in PowerShell Core Get-Module, PSCompatibility, and PSEdition The Import-Module command The Remove-Module command The Find-Module command The Install-Module command The Update-Module command The Save-Module command PowerShell Core and the WindowsCompatibility module The compatibility session Add-WindowsPSModulePath Get-WinModule and Import-WinModule Copy-WinModule Invoke-WinCommand Introducing snap-ins 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 Addition operators Subtraction operator Multiplication, division, and remainder operators Multiplication operator Division operator Remainder operator 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 Section 2: Working with Data Variables, Arrays, and Hashtables Naming and creating variables Variable commands Clear Get New Remove Set Variable provider 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 Branching and assignment Summary Working with .NET Assemblies Namespaces Types Classes Constructors Calling constructors Calling constructors with lists of arguments Arguments as an array Creating objects from hashtables Properties and methods Static properties Static methods Non-public classes Type accelerators The using keyword Using assemblies Using namespaces Summary Strings, Numbers, and Dates Manipulating strings 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 Working with comma-separated value strings Convert-String ConvertFrom-String Manipulating numbers Large byte values Power of 10 Hexadecimal Using System.Math Converting strings into numeric values Manipulating dates and times 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 The netstat command Formatting certificates Summary Files, Folders, and the Registry Working with providers Navigating Getting items Drives Items Testing for existing items Creating and deleting items Invoking items Item properties Filesystem properties Adding and removing file attributes Registry values Windows 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 Numeric values in the access control list 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 paths 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 Web Requests and Web Services Technical requirements Web requests HTTP methods HTTPS Bypassing SSL errors in Windows PowerShell Capturing SSL errors Working with REST Invoke-RestMethod Simple requests Requests with arguments Working with paging Working with authentication Using basic authentication OAuth Creating an application Getting an authorization code Requesting an access token Using a token Working with SOAP Finding a SOAP service New-WebServiceProxy Methods Methods and enumerations Methods and SOAP objects Overlapping services Summary Section 3: Automating with PowerShell Remoting and Remote Management Technical requirements WS-Management Enabling remoting Get-WSManInstance The WSMan drive Remoting and SSL Set-WSManQuickConfig Remoting and permissions Remoting permissions GUI Remoting permissions by script User Account Control Trusted hosts PSSessions New-PSSession Get-PSSession Invoke-Command Local functions and remote sessions Using splatting with ArgumentList The AsJob parameter Disconnected sessions The using variable scope The Enter-PSSession command Import-PSSession Export-PSSession Copying items between sessions 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 New-CimSession Get-CimSession Using CIM sessions Summary Asynchronous Processing Working with jobs The Start-Job, Get-Job, and Remove-Job commands The Receive-Job command The Wait-Job command Reacting to events The Register-ObjectEvent and *-Event commands The Get-EventSubscriber and Unregister-Event commands The Action, Event, EventArgs, and MessageData parameters Using Runspaces and Runspace pools Creating a PowerShell instance The Invoke and BeginInvoke methods The EndInvoke method and the PSDataCollection object 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 Runspace-synchronized objects Summary Section 4: Extending PowerShell Scripts, Functions, and Filters Introducing scripts, functions, and filters Scripts and Requires Scripts and using statements Nesting functions Comment-based help Parameter help Examples Working with long lines Line break after pipe Line break after an operator Using the array operator to break up lines Begin, process, and end Begin Process End Named blocks and return Leaky functions The Out-Null command Assigning to null Redirecting to null Casting to Void Param, parameters, and CmdletBinding Parameter types Nullable types Default values Cross-referencing parameters The CmdletBinding attribute Common parameters CmdletBinding properties ShouldProcess and ShouldContinue ShouldProcess ShouldContinue Summary 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 ValidateCount attribute The ValidateDrive attribute The ValidateLength attribute The ValidatePattern attribute The ValidateRange attribute The ValidateScript attribute The ValidateSet 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 Using PSTypeName About ValueFromPipelineByPropertyName ValueFromPipelineByPropertyName and parameter aliases Defining parameter sets Argument-completers The argument-completer attribute Using Register-ArgumentCompleter Listing registered argument-completers Dynamic parameters Creating a RuntimeDefinedParameter object Using the RuntimeDefinedParameterDictionary Using dynamic parameters Conditional parameters Summary Classes and Enumerations Defining an enumeration Enum and underlying types Automatic value assignment Enum or ValidateSet The flags attribute Using enumerations to convert values Creating a class Properties Constructors Methods Inheritance Constructor inheritance Chaining constructors The Hidden modifier The Static modifier Argument-transformation attribute classes Validation attribute classes ValidateArgumentsAttribute ValidateEnumeratedArgumentsAttribute Classes and DSC Implementing Get Implementing Set Implementing Test Using the resource Summary Building Modules Technical requirements Module layout The root module The Export-ModuleMember command Module manifest Export-ModuleMember or FunctionsToExport Side-by-side versioning Dependencies Multi-file module layout Dot-sourcing module content Merging module content Module scope Accessing module scope Initializing and removing modules The ScriptsToProcess key The OnRemove event Summary Testing Technical requirement Static analysis AST Tokenizer PSScriptAnalyzer Suppressing rules Custom script analyzer rules Creating a custom rule AST-based rules Token-based rules Using custom rules Testing with Pester Why write tests? What to test Describe and It Test cases Independent verification Assertions Testing for errors Context Before and after TestDrive Mock Assert-MockCalled Parameter filtering Mocking non-local commands Mocking objects Fabricating objects Mocking existing members Using New-MockObject Mocking CIM objects Pester in practice Summary Error Handling Error types Terminating errors Non-terminating errors Error actions Raising errors Error records Write-Error throw and ThrowTerminatingError Error and ErrorVariable Catching errors try, catch, and finally try catch finally Re-throwing errors Inconsistent error behavior throw and ErrorAction Nesting try-catch-finally Terminating or non-terminating trap Using trap trap, scope, and continue Summary Other Books You May Enjoy Leave a review - let other readers know what you think