SAVE TIME. AUTOMATE. POWERSHELL FOR SYSADMINS

Transcription

SAVE TIME.AUTOMATE. Combine commands, control flow, handle errors,write scripts, run scripts remotely, and test scriptswith the PowerShell testing framework, Pester Parse structured data like XML and JSON, work withcommon domains (like Active Directory, Azure, andAmazon Web Services), and create a real-worldserver inventory script Design and build a PowerShell module to demonstrate PowerShell isn’t just about ad-hoc scripts Use PowerShell to create a hands-off, completelyautomated Windows deployment Create endless web and SQL servers with just a fewlines of code!Real-world examples throughout help bridge the gapbetween theory and actual system, and the author’sanecdotes keep things lively.Stop relying on expensive software and fancy consultants. Learn how to manage your own environmentwith PowerShell for Sysadmins and make everyonehappy.ABOUT THE AUTHORAdam Bertram is a 20-year veteran of IT and an experienced online business professional. He’s an entrepreneur,IT influencer, Microsoft MVP, blogger, trainer, author,and content marketing writer for multiple technologycompanies. Adam is also the founder of the popular ITcareer development platform TechSnips.COVERS WINDOWS POWERSHELL v5.1w w w.nostarch.com 29.95 ( 39.95 CDN)SHELVE IN: PROGRAMMINGLANGUAGES/GENERALBERTRAMT H E F I N E ST I N G E E K E N T E RTA I N M E N T You’ll learn how to: Build an entire Active Directory forest from nothingbut a Hyper-V host and a few ISO filesPOWERSHELL FOR SYSADMINSPowerShell is both a scripting language and anadministrative shell that lets you control and automatenearly every aspect of IT. In PowerShell for Sysadmins,five-time Microsoft MVP Adam “the Automator”Bertram shows you how to use PowerShell to manageand automate your desktop and server environmentsso that you can head out for an early lunch.POW ERSHELLFOR SYSADMINS W O R K F L O WM A D EA U T O M A T I O NE A S YADAM BERTR AM

POWERSHELL FOR SYSADMINS

POWERSHELLFOR SYSADMINS Workflow AutomationMade Easyb y Ad a m B e r t r a mSan Francisco

POWERSHELL FOR SYSADMINS. Copyright 2020 by Adam Bertram.All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,electronic or mechanical, including photocopying, recording, or by any information storage or retrievalsystem, without the prior written permission of the copyright owner and the publisher.ISBN-10: 1-59327-918-3ISBN-13: 978-1-59327-918-9Publisher: William PollockProduction Editor: Janelle LudowiseCover Illustration: Josh EllingsonInterior Design: Octopod StudiosDevelopmental Editors: Alex Freed and Zach LebowskiTechnical Reviewer: Jeffery HicksCopyeditor: Sharon WilkeyCompositor: Danielle FosterProofreader: James M. FraleighIndexer: Beth Nauman-MontanaFor information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:No Starch Press, Inc.245 8th Street, San Francisco, CA 94103phone: 1.415.863.9900; info@nostarch.comwww.nostarch.comLibrary of Congress Cataloging-in-Publication DataNames: Bertram, Adam Richard author.Title: PowerShell for sysadmins / Adam Bertram.Description: San Francisco, CA : No Starch Press, 2020. Includesbibliographical references and index. Summary: "A practical guide tousing PowerShell. Begins with an introduction for new users, then moveson to explaining how to develop scripts to automate daily tasks, andfinally teaches how to build a large project to automate serverdeployments from scratch."-- Provided by publisher.Identifiers: LCCN 2019041874 (print) LCCN 2019041875 (ebook) ISBN9781593279189 (paperback) ISBN 9781593279196 (ebook)Subjects: LCSH: Windows PowerShell (Computer program language) Computernetworks--Management. Computer systems.Classification: LCC QA76.73.W56 B47 2020 (print) LCC QA76.73.W56(ebook) DDC 005.4/22--dc23LC record available at https://lccn.loc.gov/2019041874LC ebook record available at https://lccn.loc.gov/2019041875No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Otherproduct and company names mentioned herein may be the trademarks of their respective owners. Ratherthan use a trademark symbol with every occurrence of a trademarked name, we are using the names onlyin an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of thetrademark.The information in this book is distributed on an “As Is” basis, without warranty. While every precautionhas been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have anyliability to any person or entity with respect to any loss or damage caused or alleged to be caused directly orindirectly by the information contained in it.

To those that question the status quo, fightthe “that’s the way we’ve always done it”company culture, and always come up witha better solution to problems, this book isdedicated to you.

About the AuthorAdam Bertram is a 20-year veteran of IT and an experienced online business professional. He’s an entrepreneur, IT influencer, Microsoft MVP,blogger, trainer, author, and content marketing writer for multiple technology companies. Adam is also the founder of the popular IT careerdevelopment platform TechSnips (https://techsnips.io/).About the Technical ReviewerJeffery Hicks is an IT veteran with almost 30 years of experience, much ofit spent as an IT infrastructure consultant specializing in Microsoft servertechnologies with an emphasis in automation and efficiency. He is a multiyear recipient of the Microsoft MVP Award. Jeff has taught and presentedon PowerShell and the benefits of automation to IT professionals worldwide. He works today as an independent author, teacher, and consultant.

BRIEF CONTENTSAcknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xixIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiPART I: FUNDAMENTALS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Chapter 1: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Chapter 2: Basic PowerShell Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Chapter 3: Combining Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Chapter 4: Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Chapter 5: Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Chapter 6: Writing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Chapter 7: Exploring Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79Chapter 8: Running Scripts Remotely . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Chapter 9: Testing with Pester . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107PART II: AUTOMATING DAY-TO-DAY TASKS . . . . . . . . . . . . . . . . . . . . . . . . . . 113Chapter 10: Parsing Structured Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117Chapter 11: Automating Active Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137Chapter 12: Working with Azure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157Chapter 13: Working with AWS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173Chapter 14: Creating a Server Inventory Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193PART III: BUILDING YOUR OWN MODULE . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213Chapter 15: Provisioning a Virtual Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217Chapter 16: Installing an Operating System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231Chapter 17: Deploying Active Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Chapter 18: Creating and Configuring a SQL Server . . . . . . . . . . . . . . . . . . . . . . . . 253Chapter 19: Refactoring Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265Chapter 20: Creating and Configuring an IIS Web Server . . . . . . . . . . . . . . . . . . . . . 275Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285x   Brief Contents

CONTE NT S IN DE TA ILACKNOWLEDGMENTSxixINTRODUCTIONxxiWhy PowerShell? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiiWho This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiiAbout This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiiPART I: FUNDAMENTALS11GETTING STARTEDOpening the PowerShell Console . . . . . .Using DOS Commands . . . . . . . . . . . . .Exploring PowerShell Commands . . . . . .Getting Help . . . . . . . . . . . . . . . . . . . . .Displaying the Docs . . . . . . . . .Learning About General Topics .Updating the Docs . . . . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . .3.Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .Displaying and Changing a Variable .User-Defined Variables . . . . . . . . . . .Automatic Variables . . . . . . . . . . . . .Data Types . . . . . . . . . . . . . . . . . . . . . . . . . .Boolean Values . . . . . . . . . . . . . . . .Integers and Floating Points . . . . . . .Strings . . . . . . . . . . . . . . . . . . . . . .Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . .Inspecting Properties . . . . . . . . . . . . .Using the Get-Member cmdlet . . . . . .Calling Methods . . . . . . . . . . . . . . .Data Structures . . . . . . . . . . . . . . . . . . . . . . .Arrays . . . . . . . . . . . . . . . . . . . . . .ArrayLists . . . . . . . . . . . . . . . . . . . .Hashtables . . . . . . . . . . . . . . . . . . .Creating Custom Objects . . . . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . .2BASIC POWERSHELL CONCEPTS. 4. 4. 6. 8. 8. 9101113131414161920202123242525262629313335

3COMBINING COMMANDS37Starting a Windows Service . . . . . . . . . . . . .Using the Pipeline . . . . . . . . . . . . . . . . . . . .Piping Objects Between Commands .Piping Arrays Between Commands . .Looking at Parameter Binding . . . . .Writing Scripts . . . . . . . . . . . . . . . . . . . . . .Setting the Execution Policy . . . . . . .Scripting in PowerShell . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . .4CONTROL FLOW47Understanding Control Flow . . . . . . . . . . . . . . . . .Using Conditional Statements . . . . . . . . . . . . . . . .Building Expressions by Using Operators .The if Statement . . . . . . . . . . . . . . . . . . .The else Statement . . . . . . . . . . . . . . . . .The elseif Statement . . . . . . . . . . . . . . . .The switch Statement . . . . . . . . . . . . . . .Using Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . .The foreach Loop . . . . . . . . . . . . . . . . . .The for Loop . . . . . . . . . . . . . . . . . . . . .The while Loop . . . . . . . . . . . . . . . . . . .The do/while and do/until Loops . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5ERROR HANDLINGWorking with Exceptions and Errors . . . .Handling Nonterminating Errors . . . . . . .Handling Terminating Errors . . . . . . . . . .Exploring the Error Automatic Variable .Summary . . . . . . . . . . . . . . . . . . . . . . .4849495051515254545758585961.6WRITING FUNCTIONSFunctions vs. Cmdlets . . . . . . . . . . . . . . . . . . . . .Defining a Function . . . . . . . . . . . . . . . . . . . . . .Adding Parameters to Functions . . . . . . . . . . . . .Creating a Simple Parameter . . . . . . . . .The Mandatory Parameter Attribute . . . .Default Parameter Values . . . . . . . . . . .Adding Parameter Validation Attributes .xii   Contents in 4

Accepting Pipeline Input . . . . . . . . . . . . . . . . . . . .Adding Another Parameter . . . . . . . . . . .Making the Function Pipeline Compatible .Adding a process Block . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7EXPLORING MODULES79Exploring Default Modules . . . . . . . . . . . . . .Finding Modules in Your Session . . .Finding Modules on Your Computer .Importing Modules . . . . . . . . . . . . .The Components of a PowerShell Module . . .The .psm1 File . . . . . . . . . . . . . . . .The Module Manifest . . . . . . . . . . .Working with Custom Modules . . . . . . . . . .Finding Modules . . . . . . . . . . . . . .Installing Modules . . . . . . . . . . . . .Uninstalling Modules . . . . . . . . . . .Creating Your Own Module . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . .8RUNNING SCRIPTS REMOTELY.9TESTING WITH PESTER.8080818284848486868788888991Working with Scriptblocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Using Invoke-Command to Execute Code on Remote Systems .Running Local Scripts on Remote Computers . . . . . . . . . . . . .Using Local Variables Remotely . . . . . . . . . . . . . . . . . . . . . .Working with Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating a New Session . . . . . . . . . . . . . . . . . . . . . . . . . . .Invoking Commands in a Session . . . . . . . . . . . . . . . . . . . . .Opening Interactive Sessions . . . . . . . . . . . . . . . . . . . . . . .Disconnecting from and Reconnecting to Sessions . . . . . . . . .Removing Sessions with Remove-PSSession . . . . . . . . . . . . . .Understanding PowerShell Remoting Authentication . . . . . . . . . . . . . . .The Double Hop Problem . . . . . . . . . . . . . . . . . . . . . . . . . .Double Hopping with CredSSP . . . . . . . . . . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Introducing Pester . . . . . . . .Pester Basics . . . . . . . . . . . .A Pester File . . . . .The describe BlockThe context Block . .The it Block . . . . . .Assertions . . . . . . .Executing a Pester Test . . . . .Summary . . . . . . . . . . . . . .7676777778. 92. 93. 94. 95. 96. 97. 98. 98. ntents in Detail   xiii

PART II: AUTOMATING DAY-TO-DAY TASKS11310PARSING STRUCTURED DATACSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Reading CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . .Project 1: Building a Computer Inventory Report . . . . . .Excel Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating Excel Spreadsheets . . . . . . . . . . . . . . . . . . . .Reading Excel Spreadsheets . . . . . . . . . . . . . . . . . . . .Adding to Excel Spreadsheets . . . . . . . . . . . . . . . . . . .Project 2: Creating a Windows Service Monitoring Tool .JSON Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Reading JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating JSON Strings . . . . . . . . . . . . . . . . . . . . . . . .Project 3: Querying and Parsing a REST API . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315515611AUTOMATING ACTIVE DIRECTORYPrerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Installing the ActiveDirectory PowerShell Module . . . . . . . . . . . . .Querying and Filtering AD Objects . . . . . . . . . . . . . . . . . . . . . .Filtering Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Returning Single Objects . . . . . . . . . . . . . . . . . . . . . . .Project 4: Finding User Accounts That Haven’t ChangedTheir Password in 30 Days . . . . . . . . . . . . . . . . . .Creating and Changing AD Objects . . . . . . . . . . . . . . . . . . . . .Users and Computers . . . . . . . . . . . . . . . . . . . . . . . . .Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Project 5: Creating an Employee Provisioning Script . . . .Syncing from Other Data Sources . . . . . . . . . . . . . . . . . . . . . . .Project 6: Creating a Syncing Script . . . . . . . . . . . . . . .Mapping Data Source Attributes . . . . . . . . . . . . . . . . .Creating Functions to Return Similar Properties . . . . . . . .Finding Matches in Active Directory . . . . . . . . . . . . . . .Changing Active Directory Attributes . . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13712WORKING WITH AZUREPrerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Azure Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating a Service Principal . . . . . . . . . . . . . . . . . . . . .Noninteractively Authenticating with Connect-AzAccount .Creating an Azure Virtual Machine and All Dependencies . . . . . . .Creating a Resource Group . . . . . . . . . . . . . . . . . . . . . .Creating the Network Stack . . . . . . . . . . . . . . . . . . . . . .xiv   Contents in 7.157158158160161161162

Creating a Storage Account . . . . . . . . . . . . .Creating the Operating System Image . . . . . .Wrapping Up . . . . . . . . . . . . . . . . . . . . . . .Automating the VM Creation . . . . . . . . . . . . .Deploying an Azure Web App . . . . . . . . . . . . . . . . . .Creating an App Service Plan and Web App .Deploying an Azure SQL Database . . . . . . . . . . . . . . .Creating an Azure SQL Server . . . . . . . . . . . .Creating the Azure SQL Database . . . . . . . . .Creating the SQL Server Firewall Rule . . . . . . .Testing Your SQL Database . . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13WORKING WITH AWSPrerequisites . . . . . . . . . . . . . . . . . . . . . . . . . .AWS Authentication . . . . . . . . . . . . . . . . . . . . .Authenticating with the Root User . . . . . .Creating an IAM User and Role . . . . . . .Authenticating Your IAM User . . . . . . . .Creating an AWS EC2 Instance . . . . . . . . . . . . .The Virtual Private Cloud . . . . . . . . . . .The Internet Gateway . . . . . . . . . . . . . .Routes . . . . . . . . . . . . . . . . . . . . . . . . .Subnet . . . . . . . . . . . . . . . . . . . . . . . .Assigning an AMI to Your EC2 Instance .Wrapping Up . . . . . . . . . . . . . . . . . . .Deploying an Elastic Beanstalk Application . . . . .Creating the Application . . . . . . . . . . . .Deploying a Package . . . . . . . . . . . . . .Creating a SQL Server Database in AWS . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . G A SERVER INVENTORY SCRIPTPrerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating the Project Script(s) . . . . . . . . . . . . . . . . . . . . . . .Defining the Final Output . . . . . . . . . . . . . . . . . . . . . . . . .Discovery and Script Input . . . . . . . . . . . . . . . . . . . . . . . .Querying Each Server . . . . . . . . . . . . . . . . . . . . . . . . . . .Thinking Ahead: Combining Different Types of Information .Querying Remote Files . . . . . . . . . . . . . . . . . . . . . . . . . . .Querying Windows Management Instrumentation . . . . . . . .Disk Free Space . . . . . . . . . . . . . . . . . . . . . . . . .Operating System Information . . . . . . . . . . . . . . .Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Network Information . . . . . . . . . . . . . . . . . . . . . .Windows Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Script Cleanup and Optimization . . . . . . . . . . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Contents in Detail   xv

PART III: BUILDING YOUR OWN MODULE21315PROVISIONING A VIRTUAL ENVIRONMENTPowerLab Module Prerequisites . . . . . . . . . . . . . . .Creating the Module . . . . . . . . . . . . . . . . . . . . . .Creating a Blank Module . . . . . . . . . . . .Creating a Module Manifest . . . . . . . . . .Using Built-In Prefixes for Function Names .Importing the New Module . . . . . . . . . . .Automating Virtual Environment Provisioning . . . . .Virtual Switches . . . . . . . . . . . . . . . . . . .Creating Virtual Machines . . . . . . . . . . . .Virtual Hard Disks . . . . . . . . . . . . . . . . .Testing the New Functions with Pester . . . . . . . . . .Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .217.16INSTALLING AN OPERATING SYSTEMPrerequisites . . . . . . .

Design and build a PowerShell module to demon-strate PowerShell isn’t just about ad-hoc scripts Use PowerShell to create a hands-off, completely automated Windows deployment Build an entire Active Directory forest from nothing but a Hyper-V host and a few ISO files Create e