Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

PowerShell 7 Workshop: Learn how to program with PowerShell 7 on Windows, Linux, and the Raspberry Pi
PowerShell 7 Workshop: Learn how to program with PowerShell 7 on Windows, Linux, and the Raspberry Pi
PowerShell 7 Workshop: Learn how to program with PowerShell 7 on Windows, Linux, and the Raspberry Pi
Ebook1,055 pages6 hours

PowerShell 7 Workshop: Learn how to program with PowerShell 7 on Windows, Linux, and the Raspberry Pi

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateFeb 29, 2024
ISBN9781801817493
PowerShell 7 Workshop: Learn how to program with PowerShell 7 on Windows, Linux, and the Raspberry Pi

Related to PowerShell 7 Workshop

Related ebooks

Operating Systems For You

View More

Reviews for PowerShell 7 Workshop

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    PowerShell 7 Workshop - Nick Parlow

    Cover.png

    PowerShell 7 Workshop

    Copyright © 2024 Packt Publishing

    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

    1

    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

    3

    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

    Exercises

    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

    8

    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

    13

    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

    16

    Working with PowerShell and .NET

    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.

    What this book covers

    Chapter 1

    , Introduction to PowerShell – What It Is and How to Get It, explains what PowerShell 7 is, describes its uses, and how it differs from Windows PowerShell. It describes how to get it, how to install it, and how to run it, explaining the difference between User and Administrator mode. It describes how to run cmdlets and how to get help in PowerShell.

    Chapter 2

    , Exploring PowerShell Cmdlets and Syntax, focuses on how PowerShell cmdlets work, approved verbs, parameters, how to find new cmdlets with the PowerShell Gallery and elsewhere on the internet, and finally, how to work interactively with PowerShell.

    Chapter 3

    , The PowerShell Pipeline – How to String Cmdlets Together, covers how the PowerShell pipeline is one of the most important concepts in PowerShell and is quite different from how pipelines work in Bash and the Command Prompt. This chapter will show you how to successfully chain cmdlets together in a pipeline to produce useful outcomes. It will talk about filtering, output, how the pipeline works, and why it sometimes doesn’t!

    Chapter 4

    , PowerShell Variables and Data Structures, is an introduction to variables and the different types they may be, integers, floats, and how these are all objects. We’ll explore the object concept and why it is important. We’ll look at data structures as collections of objects, then arrays and hash tables, and finish with splatting.

    Chapter 5

    , PowerShell Control Flow – Conditionals and Loops, covers conditional flow (*IF* this, *THEN* that) and loops, including for, each, and while loops. Often, you won’t want to process cmdlets in a linear fashion – you’ll want to only do something if another thing is true or do something for all the objects in a pipeline. Control flow is how we do this. This chapter will also move us on from running interactive cmdlets to writing very simple scripts in VS Code.

    Chapter 6

    , PowerShell and Files – Reading, Writing, and Manipulating Data, shows you how to take data from common file types such as CSV and TXT files and manipulate it, as well as how to send your output to files, alleviating the tedium of having to read output off a screen and typing loads of it in. We’ll also cover how to output to HTML, which is great for creating formatted reports and live data in web-hosted dashboards.

    Chapter 7

    , PowerShell and the Web – HTTP, REST, and JSON, explores PowerShell and the web. Files are all very well, but a lot of cloud administration requires the manipulation of data from the internet; to do this, we’ll need to be able to manipulate the most common internet data type, JSON. We’ll also want to manipulate cloud services, for which we will need to be able to use REST API calls. This chapter will walk through that.

    Chapter 8

    , Writing Our First Script – Turning Simple Cmdlets into Reusable Code, focuses on how we can turn lines of code into a script that we can save and run over and over again. We’ve covered how to write a few lines of code in an IDE. How do we turn that into something that we would want to run repeatedly, and make it useful for other people to run?

    Chapter 9

    , Don’t Repeat Yourself – Functions and Scriptblocks, introduces you to functions in PowerShell as well as script blocks and lambdas. When writing a script, we will frequently find ourselves running the same few lines of code. Turning them into functions within the script means we only need to write it once, just calling it every time we need it.

    Chapter 10

    , Error Handling – Oh No! It’s Gone Wrong!, covers the two main types of errors that we’re likely to encounter – problems that our code encounters and problems with our code. In the first part of the chapter, we’ll define what an error is, how we can set PowerShell up to handle errors gracefully, and how we can make sense of them. In the second part, we’ll look at how we can identify problems with our code and use VS Code for debugging.

    Chapter 11

    , Creating Our First Module, examines how to turn functions and scripts into a module that can be reused, easily distributed, and incorporated into other scripts. Now we have a script, containing a set of functions, the next step is to turn that into a tool that others can use for themselves.

    Chapter 12

    , Securing PowerShell, delves into how to secure our PowerShell scripts and modules and run them in a secure fashion. PowerShell is a very powerful tool, and with great power comes great responsibility. The chapter will cover script execution policies, code signing, AppLocker, and some of the other security features.

    Chapter 13

    , Working with PowerShell 7 and Windows, explores how to use PowerShell 7 on Windows, when we will need to use PowerShell 5.1, how to interact with remote machines using WinRM, how to manage machines with CIM, and basic interaction with Windows features such as storage. PowerShell originated on Windows, and PowerShell 7 is intended to eventually replace Windows PowerShell, but we’re not there yet.

    Chapter 14

    , PowerShell 7 for Linux and macOS, explains how to install PowerShell on Linux, how it differs from running PowerShell on Windows, and how to use VS Code on Linux. It explains remoting with OpenSSH, how to run scripts, and some common administration tasks. It finishes with a section on installing and running PowerShell and VS Code on macOS.

    Chapter 15

    , PowerShell 7 and the Raspberry Pi, examines how to get started with PowerShell on Raspberry Pi, allowing us to do home automation, maker projects and more. It covers installing PowerShell and VS Code, connecting to the Pi, and running scripts. Raspberry Pi is everybody’s favorite single board computer, and we can transfer our PowerShell skills to our Pi stable.

    Chapter 16

    , Working with PowerShell and .NET, delves into .NET, which is the developer platform that PowerShell 7 is built on; it’s free, open source, and works well with VS Code. There are lots of things we can’t do easily with PowerShell alone, but we can leverage .NET to achieve them. Familiarity with .NET is an essential skill for every advanced PowerShell coder, and this chapter will help you get there.

    To get the most out of this book

    This book assumes you have a client machine, either laptop or PC, that is running Windows, Linux, or macOS. However, at a push, you can use Raspberry Pi for pretty much everything. It also assumes you have an internet connection. The majority of exercises will work on Windows, Linux and macOS; where they don’t, it’s noted. Read the first chapter, which has installation instructions for Windows, and then follow the installation instructions in the chapters on Linux/macOS or Raspberry Pi.

    If you are using the digital version of this book, I advise you to type the code yourself. Errors are part of the fun, and the sense of achievement when I realize what I’ve done wrong is not something I’d want you to miss out on.

    Conventions used

    There are a number of text conventions used throughout this book.

    Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: The application gets installed by default in C:\Users\\AppData\Local\Programs\Microsoft VS Code and is only available for the user who installed it.

    A block of code is set as follows:

    $x = 5

    if ($X -gt 4) {

        Write-Output '$x is bigger than 4'

    }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    $Array  = 1,2,3,4,5

    switch

    ($Array) {

        1 {Write-Output '$Array contains 1'}

        3 {Write-Output '$Array contains 3'}

        6 {Write-Output '$Array contains 6'}

    }

    Any command-line input or output is written as follows:

    sudo apt update

    sudo apt install ./.deb

    Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: On the Select Additional Tasks dialog, decide whether you want a desktop icon and file and directory context menu options, enabling you to open files and folders directly in VS Code.

    Tips or important notes

    Appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: If you have questions about any aspect of this book, email us at [email protected]

    and mention the book title in the subject of your message.

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata

    and fill in the form.

    Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected]

    with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com

    .

    Share your thoughts

    Once you’ve read PowerShell 7 Workshop, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page

    for this book and share your feedback.

    Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

    Download a free PDF copy of this book

    Thanks for purchasing this book!

    Do you like to read on the go but are unable to carry your print books everywhere?

    Is your eBook purchase not compatible with the device of your choice?

    Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

    Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

    The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

    Follow these simple steps to get the benefits:

    Scan the QR code or visit the link below

    https://packt.link/free-ebook/9781801812986

    Submit your proof of purchase

    That’s it! We’ll send your free PDF and other benefits to your email directly

    Part 1: PowerShell Fundamentals

    In this part, we’ll learn about the basics of PowerShell, how the language syntax works, how we can send the results of one operation straight into another with the pipeline, how PowerShell uses objects, variables, and data structures, how we can create branched and looped code, and finally, how we can write to and from stored files.

    This part has the following chapters:

    Chapter 1

    , Introduction to PowerShell – What It Is and How to Get It

    Chapter 2

    , Exploring PowerShell Cmdlets and Syntax

    Chapter 3

    , The PowerShell Pipeline – How to String Cmdlets Together

    Chapter 4

    , PowerShell Variables and Data Structures

    Chapter 5

    , PowerShell Control Flow – Conditionals and Loops

    Chapter 6

    , PowerShell and Files – Reading, Writing, and Manipulating Data

    Chapter 7

    , PowerShell and the Web – HTTP, REST, and JSON

    1

    Introduction to PowerShell 7 – What It Is and How to Get It

    Quite simply, PowerShell is a time machine. Not a science-fiction time machine where you get to go back in time and meet your own grandfather, but a real, practical one. If you put in a small amount of time, then PowerShell, like any simple machine, will act as a force multiplier; it will produce very much more time for you. To use a metaphor, it’s a time hammer, and the hours you put into learning PowerShell will save you tens or hundreds of times as many hours once you start putting the knowledge to use.

    This chapter is a general introduction to PowerShell 7. It’s going to give you some context about PowerShell and get you up and running. You’re going to learn what you can do with it and some typical use cases. We’ll be installing PowerShell, and you’ll get to choose one or more ways of doing that. Once we’ve got it installed, we’ll go through how you run commands (called cmdlets), and how you can find cmdlets to run. Finally, and quite importantly, we’ll work through how to get help, both with cmdlets and with PowerShell topics and concepts.

    In this chapter, we’re going to cover the following main topics:

    What is PowerShell 7?

    What is PowerShell 7 used for?

    Getting PowerShell 7

    Running PowerShell 7

    Getting help

    Technical requirements

    To follow along with this chapter, you will need an internet connection and an operating system. If you’re using Linux or macOS, the installation instructions can be found in Chapter 14

    , PowerShell 7 for Linux and macOS, so skip the detailed installation instructions in the How to get PowerShell 7 section, in this chapter.

    This chapter assumes that you will be using Windows 10 (version 1709 or later) running on standard 64-bit x86 architecture. If you’re not sure whether that’s what you have, don’t worry, it probably is. If you are one of life’s worriers, go to the Windows search bar and type msinfo32, then press Enter. The System Information application will open, and under System Summary, there will be three relevant lines:

    OS Name: Hopefully Microsoft Windows 10 of some flavor; PowerShell 7.3 is available on all currently supported versions of Windows.

    Version: You want a build number higher than 16299.

    System Type: Probably x64-based PC.

    The following screenshot shows how it should look under System Summary:

    Figure 1.1 – Typical information from the System Information application (msinfo32)

    Figure 1.1 – Typical information from the System Information application (msinfo32)

    If you’re using Windows 11, then good for you; you won’t need to do some of the things we’ll be talking about as Windows 11 comes with some extras.

    What is PowerShell 7?

    PowerShell is a scripting language and an alternative to the command-line interface. PowerShell is an automation tool consisting of (at least) three parts:

    A shell, like the Command Prompt in Windows or the Terminal in Linux or macOS

    A scripting language

    A configuration management framework called Desired State Configuration (DSC)

    In practice, when we talk about PowerShell, we’re usually talking about the scripting language. Usage of the shell is largely intuitive to the user, as we’ll see, and while we’ll talk about DSC later, in my experience, most people don’t use it as much as they should.

    The first version of PowerShell grew out of a project called Monad, which was an attempt by Jeffrey Snover to replicate Unix tools on Windows. He realized that one of the fundamental drawbacks of Unix tools is that they output a bytestream (usually text), and so a lot of effort is wasted on searching, formatting, and extracting the output of commands before you can act on that output. Monad was written to output objects that could be input straight into another command. We’ll cover this in more detail when we get to Chapter 4

    , PowerShell Variables and Data Structures. PowerShell 1.0 was released in 2006, but in my opinion, it didn’t really take off until PowerShell 2.0 was released in 2009, and Microsoft started re-engineering the administrative interfaces of major pieces of software such as Exchange Server 2010 to make use of it. Other opinions are available.

    At the time of writing, there are two main flavors of PowerShell: Windows PowerShell, which comes bundled with both server and desktop versions of Windows, and PowerShell 7, which must be downloaded and installed. The latest (and allegedly final) version of Windows PowerShell, v5.1, is built on .NET Framework 4.5, the proprietary software framework that is bundled with Windows and underpins many of Microsoft’s products. PowerShell 7.0 was built on .NET Core 3.1, a simplified, open source implementation of .NET. However, since version 7.2, PowerShell has been built on .NET 6.0. This unified version of .NET is a replacement for both .NET Framework and .NET Core, and was released in November 2020.

    Because of the fundamental differences between Windows PowerShell 5.1 and PowerShell 7.x, there can be some differences in how they work on the Windows platform. These will be discussed in Chapter 13

    , Working With PowerShell 7 and Windows.

    We’ll find it useful to summarize some of the key differences in the following table:

    Table 1.1 – Some differences between Windows PowerShell and PowerShell 7

    In this section, we have covered what PowerShell is, and how it differs from Windows PowerShell. In the next section, we’ll look at why PowerShell 7 exists and see what makes it special.

    What is PowerShell 7 used for?

    PowerShell is for getting things done quickly. It’s for when you need a relatively short piece of code for something that you can reuse and repurpose easily to do something else. It’s for when you don’t want to spend months learning a language, then more months writing thousands of lines of code. The language can be used in at least four ways:

    You can input single lines of code in the shell, as you would at the Windows Command Prompt or the Linux Terminal. This is great if you need to check a value, accomplish a single task such as rebooting a remote computer, or grab a log file.

    You can write a script, such as a Bash script in Linux or a batch file for Windows, that accomplishes multiple subtasks, such as gathering event logs and performance information from several machines and compiling them into a single HTML report.

    If you write a lot of scripts or need to accomplish something more complex, you can use PowerShell as a procedural programming language with multiple packaged scripts that each describe a single function and are called by a master script.

    You can use it as an object-oriented programming language and package a whole application that can be redistributed and run by anyone with PowerShell installed.

    We’ll be focusing on scripts and procedural programming in this book, as that is how most people use PowerShell. These are very similar; the difference is that in a script, you are using cmdlets that have been written for you, but in procedural programming, you are creating your own cmdlets, either from pre-existing cmdlets or by using the system programming language C#.

    Scripting languages versus system programming languages

    The PowerShell language is a scripting language. It’s for gluing other applications together quickly and easily – sort of a coding version of Lego. It relies on an underlying interpreter: the PowerShell program. Without PowerShell installed, a PowerShell script can’t run. This is quite similar to other interpreted languages, such as Python, and sits in contrast to system programming languages, such as C or C++, which are compiled into executable files. When you compile a C++ program, it can theoretically run on any compatible machine. There are other differences as well – here are some of the main ones:

    Interpreted languages are less efficient than compiled languages because each line has to be interpreted before it can run. This means they are slower than compiled programs. There are programming tricks you can use to speed things up, but performing a task in an interpreted language will pretty much always be slower than doing it in a compiled language.

    Interpreted languages are more efficient than compiled languages in development. They accomplish the same tasks with far fewer lines of code. This means that writing them, debugging them, and reusing them is much quicker. They are also much easier to learn.

    Interpreted languages can run on multiple architectures. As we’ll see in this book, code written in PowerShell can run on Windows, Linux, or macOS, with minimal tweaking. A program written in C++ for Windows can only run on Windows, or a machine with Windows emulation. It would need to be rewritten and recompiled for a different platform.

    Interpreted languages produce collaborative reusable programs. With PowerShell (or Python), you produce code that is readable and editable by humans. With a compiled language, you produce a binary file that cannot easily be decompiled into source code for reuse. This means other people can reuse your code for their own purposes. Platforms such as GitHub can be used to distribute your code, other people can contribute to it, improve it, reuse it for their programs, and act in a generally communitarian fashion.

    It boils down to this: if you want to write a super-fast first-person shooter game with spectacular graphics, then PowerShell is probably not the language for you. If you want to automate some tasks, simple or complex, then PowerShell is a good choice.

    Getting PowerShell 7

    In this section, we’ll look at some of the ways to get PowerShell onto your machine, where it goes and why, and how you can control aspects of your installation. This chapter will only cover installation on

    Enjoying the preview?
    Page 1 of 1