PowerShell Advanced Cookbook by Morten Elmstrøm Hansen
By Morten Elmstrøm Hansen

PowerShell Advanced Cookbook

A practical guide to advanced PowerShell for IT professionals who already write scripts, with recipes for building reliable and reusable automation for Windows, Active Directory, Azure, AWS and Microsoft 365.

Pages
684
Recipes
90+
Published
2024
Publisher
BPB Publications
ISBN
9789355516732
Formats
Kindle and paperback

What You Will Learn

Six of the topics the book covers, each taught through recipes that you can run, read line by line and adapt to your own work.

Advanced Functions

You learn to build one function step by step, adding parameter validation, parameter sets, pipeline input and confirmation prompts, so that we can see why each feature exists before we use it in larger scripts.

Error Handling

You learn to catch and report errors in scripts and background jobs, define your own error classes and write structured logs, so that we always know what failed and why.

Azure, AWS and Microsoft 365

You learn to manage cloud resources and Microsoft 365 applications from scripts, signing in with service principals and roles instead of stored passwords.

Secure Remote Management

You learn to run commands on remote computers with PowerShell remoting, and we compare the authentication methods and their security trade-offs before choosing one.

Testing with Pester

You learn to write unit tests for scripts with Pester and to replace the commands a script depends on with mocks, so that a test checks only your own code.

Configuration and Data

You learn to keep systems in a declared state with Desired State Configuration and to read, transform and write XML and JSON data.

Chapter Overview

Fifteen chapters, from the foundations of advanced PowerShell to managing cloud services and building applications.

01

Introduction to Advanced PowerShell Concepts

The language features and working practices that the rest of the book builds on.

02

Advanced PowerShell Functions

One function built step by step, from parameters and parameter sets to pipeline input and confirmation prompts.

03

Flow Control and Looping

Loops, conditions and switch statements, and how to choose between them for speed and memory use.

04

Error Handling

Handling errors in scripts and background jobs, with custom error classes and structured logging.

05

Scripting Techniques

Organising code, signing scripts and working with execution policies, for scripts that other people run.

06

Remote Script Execution: PowerShell Remote Management

PowerShell remoting over WinRM, with the authentication methods and their security trade-offs.

07

Testing with Pester

Unit tests for scripts with Pester, including mocks for the commands a script depends on.

08

Working with XML and JSON

Reading, transforming and writing structured data in XML and JSON.

09

Active Directory Management

Creating and managing Active Directory users and objects from scripts.

10

Managing Azure with PowerShell

Managing Azure resources from scripts that sign in with service principals.

11

Managing AWS with PowerShell

Managing AWS resources with the AWS Tools for PowerShell.

12

Microsoft 365 Applications Management

Administering Microsoft 365 applications such as Exchange Online, SharePoint and Teams.

13

Desired State Configuration

Declaring how a system should be configured and keeping it in that state, in push and pull modes.

14

Managing Windows Components

Managing Windows services, firewall rules and other system components from scripts.

15

SAPIEN PowerShell Studio IDE

Building desktop applications and Windows services from PowerShell scripts with SAPIEN PowerShell Studio.

Who This Book Is For

This book is for IT professionals who already write PowerShell scripts and want to build automation that is reliable, reusable and secure.

  • DevOps engineers who use PowerShell in their pipelines and tooling
  • System administrators who want to replace manual work with scripts
  • Cloud engineers who manage Azure, AWS or Microsoft 365
  • Team leads who want shared, tested scripts that the whole team can rely on

Prerequisites

To get the most out of this book, you should have:

  • Basic PowerShell scripting experience
  • Understanding of Windows administration concepts
  • Familiarity with command-line interfaces
  • Access to a Windows or cross-platform PowerShell environment
Recommended Version
PowerShell 7.x or later

A Recipe from the Book

This function from Chapter 4 writes structured log entries to a JSON file, and later chapters reuse it, among other places in a Windows service.

Add-LogToJson.ps1 — Chapter 4: Error Handling
function Add-LogToJson {
    <#
    .SYNOPSIS
        Writes a structured log entry to a JSON file.
    .DESCRIPTION
        Creates JSON log entries with timestamp, message, and severity.
        Uses StreamWriter for performance with high-frequency logging.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory)]
        [String]$LogFile,

        [Parameter(Position = 1, Mandatory)]
        [String]$Message,

        [ValidateSet('INFO', 'WARNING', 'ERROR', 'CRITICAL', 'DEBUG', 'OK')]
        [String]$Level = 'INFO',

        [hashtable]$Adds
    )

    BEGIN {
        # Create log file if it doesn't exist
        if (-not (Test-Path $LogFile)) {
            New-Item -Path $LogFile -ItemType File -Force | Out-Null
        }

        # Timestamp with millisecond precision
        $Time = Get-Date -Format "dd-MM-yyyy HH:mm:ss,fff"

        # Build structured log object
        $Body = @{
            timestamp = $Time
            message   = $Message
            level     = $Level
        }

        # Merge additional context if provided
        if ($Adds) { $Body = $Body + $Adds }
    }

    PROCESS {
        try {
            # StreamWriter for better performance with frequent writes
            $Stream = [System.IO.StreamWriter]::new($LogFile, $true)
            $Stream.WriteLine("$($Body | ConvertTo-Json -Compress)")
            Write-Verbose "Log written to: $LogFile"
        }
        catch {
            Write-Error "Could not create log entry: $_"
        }
        finally {
            # Always release the file handle
            try { $Stream.Close() } catch { }
        }
    }
}

# Usage: structured logging with context
Add-LogToJson "app.log" "Database connection failed" -Level ERROR -Adds @{
    server = "db01"
    error  = $_.Exception.Message
}

The book contains 90+ recipes like this one, each explained step by step.

Get the Book

PowerShell Advanced Cookbook is available from Amazon in Kindle and paperback formats.

Buy on Amazon