All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Khushboo Samkaria
Book Project Manager: Neil D'mello
Senior Editor: Romy Dias
Technical Editor: Rajat Sharma
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Vijay Kamble
DevRel Marketing Coordinator: Marylou De Mello
First published: February 2024
Production reference: 1090224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80181-298-6
For Chris, Megan, Tom, Bryn, and Mam and Dad I love you all more than I can say
Contributors
About the author
Nick Parlow is a Fujitsu Fellow and has been an email specialist for the last 20 years. He’s a Microsoft Certified Master in Exchange, a VMware Certified Advanced Professional, and a Microsoft Certified Trainer He’s got master’s degrees in network engineering from Sheffield Hallam and software engineering from Northumbria. Best of all, he’s a Raspberry Pi Certified Educator. Before IT, he worked as a metallurgist, including at the Joint European Torus, and also worked as a deckhand and a tree surgeon’s mate It’s all good He works with schools in Hertfordshire, teaching programming and physical computing In his spare time, he likes to play with chainsaws, watch Welsh rugby, listen to punk music, and drink cider
It takes a village to raise an idiot I name (some of) the guilty: Jon Funiciello and all my PTSG colleagues; Dave Snelling, Joseph Reger, and the FDEs; Beth Rowlands and Zara Brooke; Romy, Neil, Sean, and Khushboo at Packt; Craig, Steve, and Farah, the technical reviewers; Mark and Helen Kerr; Mark and Sue Custerson; Tim Parlow; Uncle Bob and Auntie Gill; Mam and Dad; Megan, Tom, and Bryn; and above all, my amazing wife, Chris
Thank you, all I owe you everything, but you’ll have to settle for beer
About the reviewers
Stephen Atherton (Steve) “fell into” IT in the late 1980s, when, as a civil servant, he was provided with a sparkling new PC and told to “get on with it!” Very soon he was hooked, creating databases and batch jobs, and soon moved on to PC and Novell NetWare support He later moved into network design when outsourced to Fujitsu (then ICL) in 1995 and progressed to CTO on a couple of major government contracts overseeing numerous network migrations and BAU. For the last 8 years, Steve has developed and maintained standard server builds and Ansible and PowerShell automation solutions Married for nearly 40 years, with 3 children and 4 grandchildren, Steve moved to Blackpool from North Wales in 1982 and enjoys nothing better than a round of golf (over 19 holes!).
My wife, Tracey, has been my rock over the many years we ’ ve been together, putting up with my absences for work and many hobbies; my family is the reason I did what I did, and I wouldn’t be anything without them! My dear friend and golf buddy, Allan, and his wife, Sue, have always helped me keep it light, get out, enjoy life, and sustain my sanity. I am my father, my mother, and my brother; may they rest in peace And remember – no rain, no rainbows!
Craig Lloyd is a computer science graduate from the late 1980s with a 34-year timeline in the IT industry His primary role has always been technical, originally in mainframe digital communications, then later, when the world adopted TCP/IP, moving into pure network infrastructure problem analysis and troubleshooting at the network packet level. More recently, he has carried forward his technical skills into the arena of server hosting, hypervisors, and hybrid infrastructures across multiple vendor cloud platforms Every day has been an opportunity to learn something new, and PowerShell, which has liberated the Command Prompt, has given Craig a platform to do that.
Table of Contents
Preface
Part 1: PowerShell Fundamentals
Introduction to PowerShell 7 – What It Is and How to Get It
Technical requirements
What is PowerShell 7?
What is PowerShell 7 used for?
Scripting languages versus system programming languages
Getting PowerShell 7
Installation from an .msi file
Installation from the .zip file
Installation with winget
Other ways to install
Running PowerShell 7
Running PowerShell with administrator privileges
Autocomplete
Getting help
Get-Command
Get-Help
Get-Member
Summary
Exercises
Further reading
2
Exploring PowerShell Cmdlets and Syntax
Technical requirements
What are cmdlets?
Exploring cmdlet structure
The correct use of aliases
Understanding cmdlet syntax
How to find more cmdlets
Finding modules and cmdlets on your machine
Finding new modules and cmdlets
Working interactively with PowerShell
Windows Terminal – an alternative terminal emulator
Installing Windows Terminal from Microsoft Store
Summary
Exercises
The PowerShell Pipeline – How to String Cmdlets Together
How to bring cmdlets together – the pipeline
What is an object?
Selecting and sorting objects
Using Select-Object
Ordering objects with Sort-Object
Filtering objects
Understanding comparison operators
Understanding Where-Object advanced syntax
Multiple filters in the advanced syntax
Filter optimization
Enumerating objects
Parallel enumeration
How the pipeline works – parameter binding
Understanding ByValue parameter binding
ByPropertyName parameter binding
Troubleshooting the pipeline – pipeline tracing
Summary
Further reading
4
PowerShell Variables and Data Structures
Understanding PowerShell variables
Variables are not their contents
Naming variables
The three common types of PowerShell variable
Exploring object types
What is an object? – redux
Discovering value types
Booleans
Integers
Real numbers
Char
Typing explained
Dynamic versus static typing
Casting variables
Navigating reference types
Arrays
Strings
Hashtables
Splatting – a cool use for hashtables
Summary
Exercises
Further reading
5
PowerShell Control Flow – Conditionals and Loops
An introduction to IDEs and VS Code
Installing VS Code
Configuring VS Code for PowerShell
Conditional control – if, else, elseif, and switch
The if statement
The switch statement
Loops – foreach, do while, do until, while, for
The foreach loop statement
The do while and do until loop statements
The while loop
The for loop
Breaking and continuing
The break statement
The continue statement
Let’s play a game
Summary
Exercises
Further reading
6 PowerShell and Files – Reading, Writing, and Manipulating Data
Understanding formatting
Format-List
Format-Table
Format-Wide
Formatting gotchas
Writing a text file
Using ConvertTo- and Export- cmdlets
CSV
XML
HTML
Handling files
A brief note about PSProviders and PSDrives
Item- cmdlets
Working with files
Get-Content
Import- cmdlets
Let’s have some fun – measuring the most frequent words in a text file
Summary
Exercises
Further reading
7
PowerShell and the Web – HTTP, REST, and JSON
Working with HTTP
Why don’t we see Forms information in PowerShell 7?
Authentication
Getting to grips with APIs
RPC APIs
SOAP APIs
REST APIs
WebSocket APIs
Working with REST Invoke-RestMethod
Working with JSON
ConvertFrom-Json
ConvertTo-Json Test-Json
Let’s have some fun – who is on the International Space Station?
Summary
Exercises Further reading
Part 2: Scripting and Toolmaking
Writing Our First Script – Turning Simple Cmdlets into Reusable Code
Introduction to scripting
Why do we want to write scripts?
Getting scripts
Running scripts
Writing a script
Identifying changing values
Working with parameters
Creating useful parameters
Specifying type
Making parameters mandatory
Taking values from the pipeline
Switch parameters
Providing help for our script
Comments
Comment-based help
Write-Verbose
Parameter help messages
Summary
Further reading
Exercises
9
Don’t Repeat Yourself – Functions and Scriptblocks
Why do we care about repeating code?
How to turn repeating code into a function
What makes a function?
Function parameters
Filters
The concept of scope
Parent and child scopes
Scope modifiers
Exploring scriptblocks
How to run a scriptblock
Lambdas
Let’s do something useful
Summary
Further reading
Exercises 10
Error Handling – Oh No! It’s Gone Wrong!
What is an error?
Terminating and non-terminating exceptions and errors
Understanding error actions
The $ErrorActionPreference variable
The -ErrorAction parameter
Catching errors
Try/Catch/Finally
Creating errors
Exploring debugging
Script instrumentation
Debugging cmdlets
Debugging with VS Code
Summary
Exercises
Further reading
11
Creating Our First Module
Working with modules
Module locations
Module autoloading
Importing modules
PowerShellGet
Writing a simple module
A word of caution – dot-sourcing
Turning a script into a module
Nested modules
More modules
Module manifests
Using scaffolding tools such as Plaster
Summary
Exercises
Further reading 12
Securing PowerShell
Why is security so important?
A PowerShell remoting whistlestop tour
Enabling PowerShell remoting
Creating a session
Joining and leaving a session
One-to-many sessions
Securing PowerShell against inadvertent mistakes
Execution policy
Other features
Running PowerShell securely
Application control
Language modes
Security servicing criteria
Software Bill of Materials
Windows Antimalware Scan Interface support
Secure Shell (SSH) remoting
Just Enough Administration
PowerShell logging
Over the shoulder logging
Deep script block logging
Module logging
Writing secure code
Storing passwords securely
Signing scripts
Parameter security
Summary
Exercises
Further reading
Part 3: Using PowerShell
Working with PowerShell 7 and Windows
Understanding PowerShell 7 and Windows PowerShell
Exploring compatibility
Which modules are compatible with PowerShell 7?
What doesn’t work with PowerShell 7
Managing machines with CIM and WMI
Introduction to CIM and WMI
Querying data
Making changes
Summary
Exercises
Further reading
14
PowerShell 7 for Linux and macOS
Technical requirements
Installing PowerShell 7
Installing PowerShell on Ubuntu 22.04
Installing PowerShell on CentOS 8 and 9
Installing PowerShell on CentOS 7
Installing VS Code
Running PowerShell on Linux
Remoting with OpenSSH
Checking that PowerShell has OpenSSH support
Installing OpenSSH on Windows
Installing OpenSSH on Linux
Running remote sessions
Authentication
PowerShell for macOS
Installing Homebrew on macOS
Installing PowerShell on macOS
Installing VS Code on macOS
Summary
Exercises
Further reading 15
PowerShell 7 and the Raspberry Pi
Technical requirements
Introduction to the Raspberry Pi
Installing PowerShell 7 and VS Code
Installing PowerShell
Installing VS Code
Connecting remotely to the Pi
Working with a headless Pi
Connecting to the Pi with PowerShell
Connecting to the Pi with VS Code
Running PowerShell on Raspberry Pi OS
Installing the IoT module
Exploring the IoT module
Simple physical computing
Summary
Questions
Further reading
Exploring .NET
Software frameworks explained
Common language infrastructure
Common language runtime – CoreCLR
Framework Class Library – CoreFX
.NET history
The uses of .NET
The components of .NET
Assemblies
Types
Enumerations
Classes
Namespaces
Members
Versioning
Working with .NET in PowerShell
PowerShell assemblies
Dynamic assembly loading
Creating instances of types
Using .NET
An alternative to the Task Scheduler
Creating GUI objects
Summary
Exercises
Further reading
Answers to Activities and Exercises
Index
Other Books You May Enjoy
Preface
PowerShell is a free, powerful, and easy-to-learn programming language Originally written as a scripting and administration tool for Windows, it’s now available as an open source resource that can be installed on almost all laptops and desktops. I have been teaching PowerShell to my colleagues for the last decade, and in my spare time, I teach coding to kids in local schools, mostly in Python. Why not teach coding with PowerShell?
Many books and courses on PowerShell assume an audience with access to multiple machines, Active Directory domains, and various other enterprise environments They often also play down the traditional coding elements of PowerShell This book does neither and attempts to teach coding with PowerShell, in a similar way to how we teach coding with Python. I’ve been inspired by the incredible work of Dr Chuck Severance of the University of Michigan – if you want to learn Python, his Python for Everybody course at py4e org is excellent
The book is split into three parts. In the first part, we cover traditional coding theory; starting with how PowerShell works as a language, we look at the building blocks of the language and then move on to how we can combine them in a programmatic flow
In the second part, we start to put together the principles we’ve learned into scripts and modules that we can share and reuse
In the final part of the book, we look at how PowerShell works in different environments, before finishing with a chapter on how we can access the underlying framework that PowerShell is built on I’ve included many interesting and varied examples and exercises in the book. To get the most out of it, I encourage you to actually type out the code, rather than just read it; the physical act of typing it drives a much deeper engagement than just scanning it ever will. Try out the questions and activities, and have a good think about the questions before skipping ahead to the answers. You’ll get much more out of the exercises if you have to work a little
I would love to hear what you think and any suggestions you have for how the book might be improved.
Who this book is for
This book is for people who want to learn to write code and want to learn it using PowerShell That might be school pupils who want to try something different, IT engineers who want to move to the next level, hobbyists, makers… everybody. It’s probably not for experienced programmers who want to add PowerShell to their impressive list of competencies; if you can already write in Java, C++, or C#, then you might do better to look at a book such as Mastering PowerShell Scripting by Chris Dent, published by Packt.
Another random document with no related content on Scribd: