Mastering Windows PowerShell Scripting, 3rd edition / Овладеваем написанием скриптов на Windows PowerShell, 3-е издание Год издания: 2019 Автор: Dent C. / Дент К. Издательство: Packt ISBN: 978-1-78953-666-9 Язык: Английский Формат: PDF Качество: Издательский макет или текст (eBook) Интерактивное оглавление: Да Количество страниц: 606 Описание: 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.
Оглавление
Preface 1 Section 1: Section 1: Exploring PowerShell Fundamentals Chapter 1: Introduction to PowerShell 8 Technical requirements 9 What is PowerShell? 9 PowerShell editors 10 Getting help 10 Updatable help 11 The Get-Help command 12 Syntax 13 Examples 14 Parameter 14 Detailed and full switches 15 Save-Help 16 Update-Help 16 About help files 18 Command naming and discovery 19 Verbs 19 Nouns 19 Finding commands 20 Aliases 21 Parameters and parameter sets 22 Parameters 22 Optional parameters 22 Optional positional parameters 23 Mandatory parameters 23 Mandatory positional parameters 23 Switch parameters 24 Common parameters 24 Parameter values 25 Parameter sets 26 Confirm, WhatIf, and Force 27 Confirm parameter 27 ConfirmPreference 28 WhatIf parameter 30 WhatIfPreference 30 Force parameter 31 Introduction to providers 31 Drives using providers 32Table of Contents [ ii ] Using providers 34 Introduction to splatting 35 Splatting to avoid escaped end-of-line 36 Splatting to avoid repetition 38 Splatting and positional parameters 39 Summary 39 Chapter 2: Modules and Snap-ins 40 Introducing modules 40 What is the PowerShell Gallery? 42 The Get-Module command 43 PSModulePath in Windows PowerShell 43 PSModulePath in PowerShell Core 44 Get-Module, PSCompatibility, and PSEdition 45 The Import-Module command 45 The Remove-Module command 47 The Find-Module command 47 The Install-Module command 48 The Update-Module command 49 The Save-Module command 49 PowerShell Core and the WindowsCompatibility module 49 The compatibility session 50 Add-WindowsPSModulePath 51 Get-WinModule and Import-WinModule 52 Copy-WinModule 52 Invoke-WinCommand 53 Introducing snap-ins 53 Using snap-ins 54 Summary 54 Chapter 3: Working with Objects in PowerShell 55 Pipelines 56 Standard output 56 Non-standard output 56 The object pipeline 57 Members 57 The Get-Member command 58 Accessing properties 59 Using methods 60 Access modifiers 61 The Add-Member command 63 Enumerating and filtering 65 The ForEach-Object command 65 Where-Object command 66 Selecting and sorting 67 The Select-Object command 67Table of Contents [ iii ] The Sort-Object command 70 Grouping and measuring 73 The Group-Object command 73 The Measure-Object command 76 Comparing 77 Importing, exporting, and converting 79 The Export-Csv command 79 The Import-Csv command 81 Export-Clixml and Import-Clixml 83 Summary 84 Chapter 4: Operators 85 Arithmetic operators 86 Operator precedence 86 Addition and subtraction operators 87 Addition operators 87 Subtraction operator 88 Multiplication, division, and remainder operators 88 Multiplication operator 89 Division operator 89 Remainder operator 90 Shift left and shift right operators 90 Assignment operators 93 Assign, add and assign, and subtract and assign 93 Multiply and assign, divide and assign, and modulus and assign 95 Comparison operators 96 Case-sensitivity 96 Comparison operators and arrays 97 Equal to and not equal to 98 Like and not like 99 Greater than and less than 99 Contains and in 100 Regular expression-based operators 101 Match and not match 101 Replace 102 Split 103 Binary operators 104 Binary and 104 Binary or 105 Binary exclusive or 105 Binary not 106 Logical operators 106 And 106 Or 107 Exclusive or 107 Not 107Table of Contents [ iv ] Type operators 108 As 108 is and isnot 109 Redirection operators 109 Redirection to a file 110 Redirecting streams to standard output 112 Redirection to null 113 Other operators 114 Call 114 Comma 114 Format 115 Increment and decrement 116 Join 117 Summary 117 Section 2: Section 2: Working with Data Chapter 5: Variables, Arrays, and Hashtables 119 Naming and creating variables 120 Variable commands 121 Clear 122 Get 122 New 122 Remove 123 Set 123 Variable provider 124 Variable scope 125 Local and global scope 126 Private scope 127 Script scope 128 Type and type conversion 129 Objects assigned to variables 131 Arrays 132 Creating an array 133 Arrays with a type 133 Adding elements to an array 134 Selecting elements from an array 135 Changing element values in an array 136 Removing elements from an array 136 Removing elements by index 137 Removing elements by value 138 Clearing an array 138 Filling variables from arrays 138 Multi-dimensional and jagged arrays 139 Hashtables 140Table of Contents [ v ] Creating a hashtable 141 Adding and changing elements to a hashtable 141 Selecting elements from a hashtable 143 Enumerating a hashtable 144 Removing elements from a hashtable 144 Lists, dictionaries, queues, and stacks 145 Lists 146 Creating a list 146 Adding elements to the list 146 Selecting elements from the list 147 Removing elements from the list 148 Changing element values in a list 148 Dictionaries 148 Creating a dictionary 149 Adding and changing elements in a dictionary 149 Selecting elements from a dictionary 150 Enumerating a dictionary 150 Removing elements from a dictionary 151 Queues 151 Creating a queue 151 Enumerating the queue 152 Adding elements to the queue 152 Removing elements from the queue 152 Stacks 153 Creating a stack 153 Enumerating the stack 153 Adding elements to the stack 154 Removing elements from the stack 154 Summary 155 Chapter 6: Branching and Looping 156 Conditional statements 156 if, else, and elseif 157 Assignment within if statements 158 switch 159 wildcard and regex 160 Expressions 161 Loops 161 foreach 161 for 162 do until and do while 162 while 163 break and continue 163 Branching and assignment 165 Summary 166 Chapter 7: Working with .NET 167 Assemblies 168Table of Contents [ vi ] Namespaces 169 Types 169 Classes 170 Constructors 170 Calling constructors 171 Calling constructors with lists of arguments 172 Arguments as an array 173 Creating objects from hashtables 176 Properties and methods 176 Static properties 178 Static methods 180 Non-public classes 182 Type accelerators 183 The using keyword 184 Using assemblies 184 Using namespaces 185 Summary 187 Chapter 8: Strings, Numbers, and Dates 188 Manipulating strings 188 Indexing into strings 188 String methods and arrays 189 Substring 190 Split 190 Replace 192 Trim, TrimStart, and TrimEnd 192 Insert and remove 193 IndexOf and LastIndexOf 194 PadLeft and PadRight 195 ToUpper, ToLower, and ToTitleCase 196 Contains, StartsWith, and EndsWith 196 Chaining methods 197 Converting strings 197 Working with Base64 197 Working with comma-separated value strings 199 Convert-String 200 ConvertFrom-String 201 Manipulating numbers 202 Large byte values 202 Power of 10 203 Hexadecimal 203 Using System.Math 203 Converting strings into numeric values 204 Manipulating dates and times 205 DateTime parameters 205Table of Contents [ vii ] Parsing dates 206 Changing dates 207 Comparing dates 209 Summary 210 Chapter 9: Regular Expressions 211 Regex basics 212 Debugging regular expressions 212 Literal characters 213 Any character (.) 214 Repetition with * and + 215 The escape character (\) 215 Optional characters 216 Non-printable characters 217 Anchors 217 Repetition 218 Exploring the quantifiers 219 Character classes 220 Ranges 220 Negated character class 222 Character class subtraction 222 Shorthand character classes 223 Alternation 223 Grouping 224 Repeating groups 224 Restricting alternation 225 Capturing values 226 Named capture groups 227 Non-capturing groups 228 Examples of regular expressions 229 MAC addresses 229 IP addresses 231 The netstat command 231 Formatting certificates 233 Summary 234 Chapter 10: Files, Folders, and the Registry 235 Working with providers 235 Navigating 236 Getting items 236 Drives 237 Items 238 Testing for existing items 238 Creating and deleting items 239 Invoking items 240Table of Contents [ viii ] Item properties 241 Filesystem properties 241 Adding and removing file attributes 241 Registry values 244 Windows permissions 245 Ownership 245 Access and audit 246 Rule protection 247 Inheritance and propagation flags 249 Removing access control entries 250 Copying lists and entries 251 Adding access control entries 252 Filesystem rights 252 Registry rights 254 Numeric values in the access control list 255 Transactions 256 File catalogs 257 New-FileCatalog 257 Test-FileCatalog 258 Summary 259 Chapter 11: Windows Management Instrumentation 260 Working with WMI 260 WMI classes 261 WMI commands 261 The WMI Query Language 262 Understanding SELECT, WHERE, and FROM 262 Escape sequences and wildcard characters 263 Logic operators 264 Comparison operators 264 Quoting values 264 Associated classes 265 WMI object paths 266 Using ASSOCIATORS OF 267 CIM cmdlets 268 Getting instances 269 Getting classes 269 Calling methods 270 Creating instances 273 Working with CIM sessions 274 Associated classes 275 The WMI cmdlets 276 Getting instances 277 Working with dates 277 Getting classes 277 Calling methods 278Table of Contents [ ix ] Creating instances 280 Associated classes 280 Permissions 281 Sharing permissions 281 Creating a shared directory 281 Getting a security descriptor 282 Adding an access control entry 284 Setting the security descriptor 285 WMI permissions 285 Getting a security descriptor 285 The access mask 285 WMI and SDDL 286 Summary 288 Chapter 12: HTML, XML, and JSON 289 HTML 289 ConvertTo-Html 289 Multiple tables 290 Adding style 290 HTML and special characters 291 XML 292 Elements and attributes 292 Namespaces 293 Schemas 293 System.Xml 294 ConvertTo-Xml 294 XML type accelerator 295 XPath and Select-Xml 295 Working with namespaces 297 Creating documents 299 Modifying element and attribute values 300 Adding elements 301 Copying nodes between documents 301 Removing elements and attributes 302 Schema validation 303 System.Xml.Linq 304 Opening documents 304 Selecting nodes 305 Creating documents 306 Working with namespaces 307 Modifying element and attribute values 308 Adding nodes 309 Removing nodes 309 Schema validation 310 JSON 311 ConvertTo-Json 311Table of Contents [ x ] ConvertFrom-Json 312 Summary 314 Chapter 13: Web Requests and Web Services 315 Technical requirements 315 Web requests 315 HTTP methods 316 HTTPS 317 Bypassing SSL errors in Windows PowerShell 318 Capturing SSL errors 319 Working with REST 321 Invoke-RestMethod 321 Simple requests 322 Requests with arguments 323 Working with paging 325 Working with authentication 327 Using basic authentication 327 OAuth 328 Creating an application 329 Getting an authorization code 329 Requesting an access token 331 Using a token 331 Working with SOAP 332 Finding a SOAP service 332 New-WebServiceProxy 333 Methods 334 Methods and enumerations 335 Methods and SOAP objects 336 Overlapping services 337 Summary 339 Section 3: Section 3: Automating with PowerShell Chapter 14: Remoting and Remote Management 341 Technical requirements 341 WS-Management 342 Enabling remoting 342 Get-WSManInstance 343 The WSMan drive 343 Remoting and SSL 343 Set-WSManQuickConfig 344 Remoting and permissions 346 Remoting permissions GUI 346 Remoting permissions by script 347 User Account Control 350 Trusted hosts 351 PSSessions 351Table of Contents [ xi ] New-PSSession 352 Get-PSSession 352 Invoke-Command 353 Local functions and remote sessions 354 Using splatting with ArgumentList 354 The AsJob parameter 355 Disconnected sessions 355 The using variable scope 356 The Enter-PSSession command 357 Import-PSSession 357 Export-PSSession 358 Copying items between sessions 358 Remoting on Linux 359 Remoting over SSH 360 Connecting from Windows to Linux 360 Connecting from Linux to Windows 361 The double-hop problem 364 CredSSP 364 Passing credentials 365 CIM sessions 365 New-CimSession 366 Get-CimSession 367 Using CIM sessions 367 Summary 368 Chapter 15: Asynchronous Processing 369 Working with jobs 369 The Start-Job, Get-Job, and Remove-Job commands 370 The Receive-Job command 371 The Wait-Job command 372 Reacting to events 373 The Register-ObjectEvent and *-Event commands 374 The Get-EventSubscriber and Unregister-Event commands 376 The Action, Event, EventArgs, and MessageData parameters 376 Using Runspaces and Runspace pools 378 Creating a PowerShell instance 379 The Invoke and BeginInvoke methods 380 The EndInvoke method and the PSDataCollection object 382 Running multiple instances 384 Using the RunspacePool object 385 About the InitialSessionState object 386 Adding modules and snap-ins 387 Adding variables 388 Adding functions 389 Using the InitialSessionState and RunspacePool objects 390 Using Runspace-synchronized objects 390Table of Contents [ xii ] Summary 392 Section 4: Section 4: Extending PowerShell Chapter 16: Scripts, Functions, and Filters 394 Introducing scripts, functions, and filters 394 Scripts and Requires 395 Scripts and using statements 395 Nesting functions 396 Comment-based help 396 Parameter help 398 Examples 400 Working with long lines 400 Line break after pipe 401 Line break after an operator 401 Using the array operator to break up lines 401 Begin, process, and end 403 Begin 404 Process 404 End 405 Named blocks and return 406 Leaky functions 407 The Out-Null command 408 Assigning to null 409 Redirecting to null 409 Casting to Void 409 Param, parameters, and CmdletBinding 410 Parameter types 410 Nullable types 411 Default values 411 Cross-referencing parameters 412 The CmdletBinding attribute 413 Common parameters 413 CmdletBinding properties 414 ShouldProcess and ShouldContinue 415 ShouldProcess 415 ShouldContinue 417 Summary 420 Chapter 17: Parameters, Validation, and Dynamic Parameters 421 The Parameter attribute 421 Position and positional binding 423 The DontShow property 425 The ValueFromRemainingArguments property 426 The HelpMessage property 427 Validating input 428 The PSTypeName attribute 428Table of Contents [ xiii ] Validation attributes 430 The ValidateNotNull attribute 431 The ValidateNotNullOrEmpty attribute 432 The ValidateCount attribute 432 The ValidateDrive attribute 433 The ValidateLength attribute 433 The ValidatePattern attribute 433 The ValidateRange attribute 435 The ValidateScript attribute 436 The ValidateSet attribute 437 The Allow attributes 437 The AllowNull attribute 437 The AllowEmptyString attribute 438 The AllowEmptyCollection attribute 438 PSReference parameters 439 Pipeline input 440 About ValueFromPipeline 440 Accepting null input 441 Input object types 442 Using ValueFromPipeline for multiple parameters 443 Using PSTypeName 444 About ValueFromPipelineByPropertyName 445 ValueFromPipelineByPropertyName and parameter aliases 446 Defining parameter sets 447 Argument-completers 451 The argument-completer attribute 452 Using Register-ArgumentCompleter 452 Listing registered argument-completers 453 Dynamic parameters 454 Creating a RuntimeDefinedParameter object 456 Using the RuntimeDefinedParameterDictionary 457 Using dynamic parameters 458 Conditional parameters 460 Summary 461 Chapter 18: Classes and Enumerations 462 Defining an enumeration 462 Enum and underlying types 463 Automatic value assignment 464 Enum or ValidateSet 465 The flags attribute 465 Using enumerations to convert values 467 Creating a class 467 Properties 468 Constructors 469 Methods 470 Inheritance 471Table of Contents [ xiv ] Constructor inheritance 471 Chaining constructors 472 The Hidden modifier 473 The Static modifier 474 Argument-transformation attribute classes 475 Validation attribute classes 477 ValidateArgumentsAttribute 477 ValidateEnumeratedArgumentsAttribute 478 Classes and DSC 480 Implementing Get 482 Implementing Set 483 Implementing Test 484 Using the resource 485 Summary 488 Chapter 19: Building Modules 489 Technical requirements 489 Module layout 490 The root module 490 The Export-ModuleMember command 491 Module manifest 492 Export-ModuleMember or FunctionsToExport 494 Side-by-side versioning 494 Dependencies 495 Multi-file module layout 495 Dot-sourcing module content 496 Merging module content 498 Module scope 499 Accessing module scope 501 Initializing and removing modules 502 The ScriptsToProcess key 502 The OnRemove event 502 Summary 503 Chapter 20: Testing 504 Technical requirement 504 Static analysis 505 AST 505 Tokenizer 506 PSScriptAnalyzer 508 Suppressing rules 509 Custom script analyzer rules 510 Creating a custom rule 510 AST-based rules 511 Token-based rules 512 Using custom rules 512Table of Contents [ xv ] Testing with Pester 513 Why write tests? 514 What to test 514 Describe and It 515 Test cases 517 Independent verification 518 Assertions 519 Testing for errors 519 Context 522 Before and after 522 TestDrive 526 Mock 526 Assert-MockCalled 527 Parameter filtering 528 Mocking non-local commands 529 Mocking objects 531 Fabricating objects 531 Mocking existing members 533 Using New-MockObject 535 Mocking CIM objects 537 Pester in practice 538 Summary 543 Chapter 21: Error Handling 544 Error types 544 Terminating errors 545 Non-terminating errors 545 Error actions 546 Raising errors 547 Error records 547 Write-Error 549 throw and ThrowTerminatingError 550 Error and ErrorVariable 551 Catching errors 553 try, catch, and finally 553 try 553 catch 553 finally 555 Re-throwing errors 556 Inconsistent error behavior 559 throw and ErrorAction 561 Nesting try-catch-finally 563 Terminating or non-terminating 565 trap 566 Using trap 566 trap, scope, and continue 567 Summary 568Table of Contents [ xvi ] Other Books You May Enjoy 569 Index 572
Dent C. / Дент К. - Mastering Windows PowerShell Scripting, 3rd edition / Овладеваем написанием скриптов на Windows PowerShell, 3-е издание [2019, PDF, ENG] download torrent for free and without registration
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum