Mastering Windows PowerShell Scripting, Second Edition

One-stop guide to automating administrative tasks

Chris Dent . Brenton J.W. Blawat


e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 2.50 USD
 Pages
 428 p
 File Size
 2,277 KB
 File Type
 PDF format
 ISBN
 978-1-78712-630-5
 Copyright   
 2017 Packt Publishing 

About the Author
Chris Dent is a professional PowerShell developer based in and around London with over 8
years experience in that language alone. He is also proficient in C#, VBScript, Perl, and
Python, but PowerShell is his favorite by a wide margin. He is also the author of dnshell.
He describes himself as being a toolset or module developer (he rarely writes scripts in the
one-off sense); he has a deep interest in formalized development approaches, continuous
integration, secure coding practices, and creating supportable automation frameworks
within organizations.

Brenton J.W. Blawat is an entrepreneur, strategic technical advisor, author, and enterprise
architect, who has a passion for the procurement of technology in profit-based
organizations. He is business-centric and technology-minded. Brenton has many years of
experience in bridging the gap between technical staff and decision-makers in several
organizations. He takes pride in his ability to effectively communicate with a diverse
audience and provide strategic direction for large and small organizations alike.
In 2013, Brenton authored his first book, PowerShell 3.0 WMI Starter, Packt Publishing. In
March 2015, he authored his second book, Mastering Windows PowerShell Scripting, with Packt Publishing.
Brenton currently works at CDW as an Enterprise Architect in strategic solutions and
services. CDW is a leading multibrand technology solutions provider in the fields of
business, government, education, and healthcare. A Fortune 500 company, it was founded
in 1984 and employs approximately 7,200 coworkers. In 2016, the company generated net
sales of more than $13.0 billion.
His current specialization sits on top of 15 years of experience spread across (predominantly
Microsoft) systems, (Juniper and Cisco) networking, and security.

About the Reviewer
Paul Broadwith is a senior technology professional freelancing in Scotland. He has over 25
years of experience in diverse sectors, from manufacturing and financial services to the
public sector and managed IT services.

With particular expertise in Microsoft and Linux technologies, he has interest in PowerShell
on both platforms. An advocate of a common-sense approach to coding, best practice, and
code reusability, he enjoys practicing what he preaches in his code and mentoring new professionals.

Table of Contents
Preface 1
Chapter 1: Introduction to PowerShell 6
What is PowerShell? 7
Quick reference 7
Comments 7
Special characters 7
Tick in PowerShell 7
Common operators 9
Dropping unwanted output 9
Creating arrays and hashtables 9
Strings 10
Common reserved variables 11
Quick commands and hot keys 12
PowerShell editors 12
PowerShell ISE 13
Features 14
Installing ISE Preview 14
Starting ISE 15
Visual Studio Code 15
Features 15
Console 16
Version control (Git) 18
PowerShell on Linux 19
Installing PowerShell 20
Where are the PowerShell files? 20
Changing the shell 21
Profiles 21
Multiplatform scripting 22
Line endings 23
File encoding 23
Path separator 24
Example 24
Summary 25
Chapter 2: Working with PowerShell 26
Getting help 26
Updatable help 27
The Get-Help command 28
Syntax 29
Examples 29
Parameter 30
Detailed and Full switches 30
Save-Help 31
Update-Help 32
About help files 33
Command naming and discovery 34
Verbs 34
Nouns 35
Finding commands 35
Aliases 36
Parameters and parameter sets 37
Parameters 37
Optional parameters 37
Optional positional parameters 38
Mandatory parameters 38
Mandatory positional parameters 38
Switch parameters 39
Common parameters 39
Parameter values 40
Parameter sets 41
Confirm, WhatIf, and Force 42
Confirm parameter 42
ConfirmPreference 43
WhatIf parameter 45
WhatIfPreference 45
Force parameter 46
Providers 46
Drives using providers 47
Using providers 49
Summary 51
Chapter 3: Modules and Snap-Ins 52
What is a module? 53
What is the PowerShell Gallery? 54
The Get-Module command 56
The Import-Module command 57
The Remove-Module command 58
The Find-Module command 59
The Install-Module command 59
The Save-Module command 60
What is a snap-in? 60
Using snap-ins 61
Summary 62
Chapter 4: Working with Objects in PowerShell 63
Pipelines 64
Standard output 64
Non-standard output 64
The object pipeline 65
Members 65
The Get-Member command 66
Accessing properties 67
Using methods 68
Access modifiers 70
The Add-Member command 72
Enumerating and filtering 72
The ForEach-Object command 72
Where-Object command 73
Selecting and sorting 73
The Select-Object command 74
The Sort-Object command 77
Grouping and measuring 79
The Group-Object command 79
The Measure-Object command 82
Comparing 83
Importing, exporting, and converting 85
The Export-Csv command 85
The Import-Csv command 87
Export-Clixml and Import-Clixml 88
Summary 89
Chapter 5: Operators 90
Arithmetic operators 90
Operator precedence 91
Addition and subtraction operators 91
Multiplication, division, and modulus operators 93
Shift left and shift right operators 94
Assignment operators 97
Assign, add and assign, and subtract and assign 97
Multiply and assign, divide and assign, and modulus and assign 99
Comparison operators 100
Case-sensitivity 101
Comparison operators and arrays 101
Equal to and not equal to 102
Like and not like 103
Greater than and less than 103
Contains and in 104
Regular-expression-based operators 104
Match and not match 105
Replace 106
Split 107
Binary operators 107
Binary and 108
Binary or 108
Binary exclusive or 109
Binary not 109
Logical operators 110
And 110
Or 110
Exclusive or 111
Not 111
Type operators 112
As 112
Is and isnot 112
Redirection operators 113
Redirection to a file 114
Redirecting streams to standard output 115
Redirection to null 116
Other operators 117
Call 117
Comma 117
Format 118
Increment and decrement 118
Join 119
Summary 120
Chapter 6: Variables, Arrays, and Hashtables 121
Naming and creating variables 122
Variable commands 123
Clear-Variable 123
Get-Variable 124
New-Variable 124
Remove-Variable 125
Set-Variable 125
Variable scope 126
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 134
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 139
Multi-dimensional and jagged arrays 139
Hashtables 140
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 149
Creating a dictionary 149
Adding and changing elements in a dictionary 149
Selecting elements from a dictionary 150
Enumerating a dictionary 151
Removing elements from a dictionary 151
Queues 151
Creating a queue 152
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 154
Adding elements to the stack 154
Removing elements from the stack 154
Summary 155
Chapter 7: 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 164
Summary 165
Chapter 8: Working with .NET 166
Assemblies 167
Namespaces 168
Types 168
Classes 169
Constructors 169
Calling constructors 171
Calling constructors with lists of arguments 171
Arguments as an array 173
Properties and methods 174
Static properties 176
Static methods 178
Non-public classes 180
Type accelerators 181
Using 182
Using assemblies 182
Using namespaces 182
Summary 184
Chapter 9: Data Parsing and Manipulation 185
String manipulation 185
Indexing into strings 185
String methods and arrays 186
Substring 187
Split 187
Replace 189
Trim, TrimStart, and TrimEnd 189
Insert and Remove 190
IndexOf and LastIndexOf 191
PadLeft and PadRight 192
ToUpper, ToLower, and ToTitleCase 192
Contains, StartsWith, and EndsWith 193
Chaining methods 194
Converting strings 194
Working with Base64 194
How Base64 works 196
Working with CSV 198
Convert-String 199
ConvertFrom-String 200
Number manipulation 201
Large byte values 201
Power-of-10 202
Hexadecimal 202
Using System.Math 202
Converting strings to numeric values 203
Date and time manipulation 203
DateTime parameters 204
Parsing dates 204
Changing dates 206
Comparing dates 207
Summary 208
Chapter 10: Regular Expressions 209
Regex basics 210
Debugging regular expressions 210
Literal characters 211
Any character (.) 212
Repetition with * and + 213
The escape character (\) 213
Optional characters 214
Non-printable characters 214
Anchors 215
Repetition 216
Exploring the quantifiers 217
Character classes 218
Ranges 218
Negated character class 220
Character class subtraction 220
Shorthand character classes 221
Alternation 221
Grouping 222
Repeating groups 222
Restricting alternation 223
Capturing values 224
Named capture groups 225
Non-capturing groups 227
Examples of regular expressions 228
MAC addresses 228
IP addresses 229
Netstat command 230
Summary 232
Chapter 11: Files, Folders, and the Registry 233
Working with providers 233
Navigating 234
Getting items 234
Drives 235
Items 236
Testing existence 236
Creating and deleting items 237
Invoking items 238
Item properties 238
Filesystem properties 238
Adding and removing file attributes 239
Registry values 240
Permissions 241
Ownership 242
Access and audit 243
Rule protection 243
Inheritance and propagation flags 246
Removing access control entries 247
Copying lists and entries 248
Adding access control entries 249
Filesystem rights 250
Registry rights 251
Transactions 252
File catalogs 253
New-FileCatalog 253
Test-FileCatalog 254
Summary 255
Chapter 12: Windows Management Instrumentation 256
Working with WMI 256
WMI classes 257
WMI commands 257
The WMI Query Language 258
Understanding SELECT, WHERE, and FROM 258
Escape sequences and wildcard characters 259
Logic operators 260
Comparison operators 260
Quoting values 261
Associated classes 261
WMI object path 262
Using ASSOCIATORS OF 263
CIM cmdlets 264
Getting instances 265
Getting classes 265
Calling methods 266
Creating instances 268
Working with CIM sessions 269
Associated classes 271
The WMI cmdlets 272
Getting instances 272
Working with dates 273
Getting classes 273
Calling methods 273
Creating instances 276
Associated classes 276
Permissions 276
Sharing permissions 276
Creating a shared directory 277
Getting a security descriptor 277
Adding an access control entry 279
Setting the security descriptor 280
WMI permissions 280
Getting a security descriptor 281
The access mask 281
WMI and SDDL 281
Summary 283
Chapter 13: HTML, XML, and JSON 284
HTML 284
ConvertTo-Html 284
Multiple tables 285
Adding style 285
HTML and special characters 286
XML 287
Elements and attributes 287
Namespaces 288
Schemas 288
System.Xml 289
ConvertTo-Xml 289
XML type accelerator 290
XPath and Select-Xml 291
Working with namespaces 292
Creating documents 293
Modifying element and attribute values 294
Adding elements 295
Copying nodes between documents 296
Removing elements and attributes 297
Schema validation 297
System.Xml.Linq 298
Opening documents 299
Selecting nodes 299
Creating documents 300
Working with namespaces 301
Modifying element and attribute values 302
Adding nodes 303
Removing nodes 303
Schema validation 304
JSON 305
ConvertTo-Json 305
ConvertFrom-Json 306
Summary 308
Chapter 14: Working with REST and SOAP 309
Web requests 309
HTTP methods 310
HTTPS 310
Bypassing SSL errors 311
Capturing SSL errors 312
Working with REST 314
Invoke-RestMethod 314
Simple requests 314
Requests with arguments 315
Working with authentication 316
Walking through OAuth 316
Creating an application 317
Getting an authorization code 318
Requesting an access token 319
Getting a list of playlists 320
Getting a list of tracks 320
Working with SOAP 321
New-WebServiceProxy 321
Methods 322
Types 323
Namespaces 325
Summary 326
Chapter 15: Remoting and Remote Management 327
WS-Management 327
Enabling remoting 328
Get-WSManInstance 328
WSMan drive 329
Remoting and SSL 329
Set-WSManQuickConfig 330
Remoting and permissions 331
Remoting permissions GUI 331
Remoting permissions by script 333
User Account Control 335
Trusted hosts 336
CIM sessions 337
New-CimSession 337
Get-CimSession 338
Using CIM sessions 338
PS sessions 338
New-PSSession 339
Get-PSSession 339
Invoke-Command 339
Local functions and remote sessions 340
Using splatting with ArgumentList 341
The AsJob parameter 342
Disconnected sessions 342
The using variable scope 343
Enter-PSSession 344
Import-PSSession 344
Export-PSSession 344
Copying items between sessions 345
The double-hop problem 345
CredSSP 346
Passing credentials 347
Summary 347
Chapter 16: Testing 348
Static analysis 348
Abstract syntax tree 349
PSScriptAnalyzer 350
Suppressing rules 351
Testing with Pester 352
Why write tests? 352
What to test 353
Describe and It 353
Test cases 355
Independent verification 357
Assertions 357
Be 358
BeIn 358
BeLessThan 358
BeLike 358
BeLikeExactly 358
BeNullOrEmpty 358
BeOfType 359
FileContentMatch 359
FileContentMatchExactly 359
FileContentMatchMultiline 359
Exist 359
Match 360
MatchExactly 360
Throw 360
Not 361
Context 361
Before and After 362
TestDrive 364
Mock 365
Assert-MockCalled 365
Parameter filtering 366
Mocking objects 367
Fabricating objects 367
Mocking methods 368
CIM objects 368
Pester in practice 369
Summary 372
Chapter 17: Error Handling 373
Error types 373
Terminating errors 374
Non-terminating errors 374
Error action 375
Raising errors 376
Error records 376
Write-Error 378
Throw and ThrowTerminatingError 379
Error and ErrorVariable 380
Catching errors 381
Try, catch, and finally 381
Try 382
Catch 382
Finally 384
Rethrowing errors 384
Inconsistent error behavior 386
Throw and ErrorAction 388
Nesting try-catch-finally 391
Terminating or non-terminating 392
Trap 393
Using trap 394
Trap, scope, and continue 394
Summary 395
Index 396

Bookscreen
e-book shop

Preface
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, along with tips to make you a PowerShell scripting expert.

What this book covers
Chapter 1, Introduction to PowerShell, introduces PowerShell and why it is applicable to the
IT community. This chapter discusses the types of Microsoft systems that leverage
PowerShell and why it's important to learn this scripting language.
Chapter 2, Working with PowerShell, talks about finding and using commands and parameters.
Chapter 3, Modules and Snap-Ins, shows how to use PowerShell modules and snap-ins.
Chapter 4, Working with Objects in PowerShell, shows how to work with objects in PowerShell.
Chapter 5, Operators, shows how to use operators to test and manipulate data.
Chapter 6, Variables, Arrays, and Hashtables, explains the different mechanisms within
PowerShell that are able to store data. These include variables, hashes, and arrays.
Chapter 7, Branching and Looping, shows how to explore conditional statements and how to implement loops in PowerShell.
Chapter 8, Working with .NET, shows how to work with existing classes from the .NET framework in PowerShell.
Chapter 9, Data Parsing and Manipulation, explains different methods to manipulate simple types in PowerShell.
Chapter 10, Regular Expressions, shows the usage of regular expressions in PowerShell
scripts. This will provide the user with the ability to provide quick data comparisons.
Chapter 11, Files, Folders and the Registry, explores different methods to interact with common items on the file system and registry.
Chapter 12, Windows Management Instrumentation, explores PowerShell’s ability to interact
with WMI. This includes methods by which users can manipulate the WMI to obtain information pertaining to an operating system.
Chapter 13, HTML, XML, and JSON, explores the XML structure and how PowerShell can
interact with XML files. This chapter will also explore how to use XML files as answer files for PowerShell scripts.
Chapter 14, Working with REST and SOAP, shows how to use REST or SOAP interfaces.
Chapter 15, Remoting and Remote Management, explores the use of Windows remoting and remote sessions to execute against remote systems.
Chapter 16, Testing, shows how to use PSScriptAnalyzer and Pester to improve the quality of your code.
Chapter 17, Error Handling, shows how to leverage PowerShell’s error handling to work with errors.

What you need for this book
For this book, you will need Windows 7 or 10 and PowerShell 5.0 or 5.1. Nothing else is
mandatory or used.

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.
Loading...
DMCA.com Protection Status