Windows Server 2016 Automation with PowerShell Cookbook - Second Edition - Thomas Lee - E-Book

Windows Server 2016 Automation with PowerShell Cookbook - Second Edition E-Book

Thomas Lee

0,0
55,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Over 100 recipes to help you leverage PowerShell to automate Windows Server 2016 manual tasks

About This Book

  • Automate Windows server tasks with the powerful features of the PowerShell Language
  • Master new features such as DevOps, containers, and Nano servers, and speed up their performance using PowerShell
  • Improve PowerShell's usability, and control and manage Windows-based environments by working through inviting recipes

Who This Book Is For

If you are a systems administrator, engineer, or an architect working with Windows Server 2016 and want to automate tasks with PowerShell, then this book is for you. A basic knowledge of PowerShell is expected.

What You Will Learn

  • Streamline routine administration processes
  • Improve the performance and storage of your Windows server with enhanced large-scale PowerShell scripts
  • Use DSC to leverage Windows server features
  • Generate automatic reports that highlight unexpected changes in your environment
  • Monitor performance and report on system utilization using detailed graphs and analysis
  • Create and manage a reliable and redundant Hyper-V environment
  • Manage your enterprise's patch level
  • Utilize multiple tools and protocols to manage your environment

In Detail

This book showcases several ways that Windows administrators can use to automate and streamline their job. You'll start with the PowerShell and Windows Server fundamentals, where you'll become well versed with PowerShell and Windows Server features.

In the next module, Core Windows Server 2016, you'll implement Nano Server, manage Windows updates, and implement troubleshooting and server inventories. You'll then move on to the Networking module, where you'll manage Windows network services and network shares.

The last module covers Azure and DSC, where you will use Azure on PowerShell and DSC to easily maintain Windows servers.

Style and approach

This is a practical guide packed with attractive recipes to help you effectively use PowerShell to accelerate your daily administrative tasks with Windows server.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 568

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Windows Server 2016 Automation with PowerShell Cookbook

Second Edition

 

 

 

 

 

 

 

 

 

 

Automate manual administrative tasks with ease

 

 

 

 

 

 

 

 

 

 

Thomas Lee

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

 

Windows Server 2016 Automation with PowerShell Cookbook

Second Edition

 

Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

 

First published: October 2015

Second edition: September 2017

Production reference: 1190917

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78712-204-8

 

www.packtpub.com

Credits

Author

Thomas Lee

 

Copy Editors

Safis Editing

Juliana Nair

Reviewer

Mike F Robbins

Project Coordinator

Judie Jose

Acquisition Editor

Meeta Rajani

Proofreader

Safis Editing

Content Development Editor

Abhishek Jadhav

Indexer

Aishwarya Gangawane

Technical Editor

Mohd Riyan Khan

Graphics

Kirk D'Penha

Production Coordinator

Aparna Bhagat

About the Author

Thomas Lee is a consultant/trainer/writer from England and has been in the IT business since the late 1960's. After graduating from Carnegie Mellon University, Thomas joined ComShare where he was a systems programmer building the Commander II time-sharing operating system, a forerunner of today's Cloud computing paradigm. He moved to Comshare UK in 1975 and later went to work for ICL, again developing operating systems. After a sabbatical in 1980/81, he joined Arthur Andersen Management Consultants (now known as Accenture). He left in 1988 to run his own consulting and training business, which is still active today.

Thomas holds numerous Microsoft certifications, including MCSE (one of the first in the world) and later versions, MCT (22 years), and was awarded Microsoft's MVP award 17 times. He is also a Fellow of the British Computer Society. He has written extensively for the UK trade press, including PC Pro.

Today, Thomas writes and talks mainly on PowerShell and Azure. He currently works for a number of clients to deliver training and to build training courses. Having traveled the world, he entered semi-retirement in 2016 and is spending more time at his cottage in the English countryside, along with his wife, Susan, and their daughter, Rebecca. He continues to give back to the community and spends a lot of time as group administrator for the PowerShell forum on Spiceworks, where he is also a Moderator.

Acknowledgment

I’d first like to thank Jeffrey Snover of Microsoft for the invention of PowerShell. I was lucky enough to be in the room the very first time he presented what was then called Monad. His enthusiasm was infectious, and 15 years later I am still excited.

Also, a shout out to the author of the first edition, Ed Goad. His first edition was a great base to work on although all the recipes in this edition are reworked totally.

A huge thank you has to go to the Packt team: Meeta Rajani, Abhishek Jadhav, Mohd Riyan Khan, and Judie Jose. You guys did a great job getting this book out of the door and dealing with the crises that arose during the writing. And thanks too to our most excellent tech reviewer Mike Robbins. Your reviews were always excellent.

When I began this project, I had a co-author, David Cobb. Sadly, for personal reasons, he had to drop out, but I thank him for the chapters he was able to write. We had a large number of volunteer reviewers who read through the various chapters. I appreciate all the work you folks did to try to make this a better book.

As each recipe evolved, I would sometimes hit problems. I got a lot of help from the Spiceworks community. Their PowerShell forum is a great source of information and encouragement. If you have problems with PowerShell, this is a great place to get a solution.

And finally, I have to thank my wonderful wife, Susan. She has been patient as things progressed, she put up with my bad moods when progress was not as smooth as desirable, and kept me sane when all around me was craziness.

About the Reviewer

Mike F. Robbins is a Microsoft MVP on Windows PowerShell and a SAPIEN Technologies MVP. He is a co-author of Windows PowerShell TFM 4th Edition and is a contributing author of a chapter in the PowerShell Deep Dives book. Mike has written guest blog articles for the Hey, Scripting Guy! blog, PowerShell Magazine, and PowerShell.org. He is the winner of the advanced category in the 2013 PowerShell Scripting Games. Mike is also the leader and co-founder of the Mississippi PowerShell User Group. He blogs at mikefrobbins.com and can be found on Twitter at @mikefrobbins.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.

If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Getting the most from this book

Sections

Chapter and Recipe Headings

Getting ready

How to do it...

How it works...

There's more...

Conventions

Reader feedback

Customer support

Downloading the color images of this book

Errata

Piracy

Questions

Help and assistance

What's New in PowerShell and Windows Server

Introduction

Exploring Remote Server Administration Tools (RSAT)

How to do it...

How it works...

There's more...

Discovering new cmdlets in PowerShell 4 and Windows Server 2012 R2

New cmdlets

How to do it...

How it works...

There's more...

Discovering new cmdlets in PowerShell 5/5.1 and Windows Server 2016

Getting ready

PowerShellGet module

PackageManagement module

Microsoft.PowerShell.Archive module

Microsoft.PowerShell.Utility module

Other new modules

Other new cmdlets

How to do it...

How it works...

There's more...

Exploring PowerShellGet

How to do it...

How it works...

There's more...

Exploring PackageManagement

How to do it...

How it works...

There's more...

Creating an internal PowerShell repository

How to do it...

How it works...

There's more...

Implementing Nano Server

Introduction

Deploying a Nano Server in a VM

Getting ready

How to do it...

How it works...

There's more...

Connecting to and managing a Nano Server

Getting ready

How to do it...

How it works...

There's more...

Installing features with Nano Server packages

Getting ready

How to do it...

How it works...

There's more...

Managing Windows Updates

Introduction

Installing Windows Server Update Services

Getting ready

How to do it...

How it works...

There's more...

Configuring WSUS update synchronization

Getting ready

How to do it...

How it works...

There's more...

Configuring the Windows Update client

Getting ready

How to do it...

How it works...

There's more...

Creating computer target groups

Getting ready

How to do it...

How it works...

There's more...

Configuring WSUS auto-approvals

Getting ready

How to do it...

How it works...

There's more...

Managing updates

Getting ready

How to do it...

How it works...

There's more...

Managing Printers

Introduction

Installing and sharing printers

Getting ready

How to do it...

How it works...

Publishing a printer

Getting ready

How to do it...

How it works...

There's more...

Changing the spool directory

Getting ready

How to do it...

How it works...

Changing printer drivers

Getting ready

How to do it...

How it works...

Printing a test page on a printer

Getting ready

How to do it...

How it works...

Reporting on printer security

Getting ready

How to do it...

How it works...

Modifying printer security

Getting ready

How to do it...

How it works...

Deploying shared printers

Getting ready

How to do it...

How it works...

There's more...

Enabling Branch Office Direct Printing

Getting ready

How to do it...

How it works...

There's more...

Creating a printer pool

Getting ready

How to do it...

How it works...

Reporting on printer usage

Getting ready

How to do it...

How it works...

There's more...

Managing Server Backup

Introduction

Configure and set backup policy

Getting ready

How to do it...

How it works...

There's more...

Examine the results of a backup

Getting ready

How to do it...

How it works...

There's more...

Initiate a backup manually

Getting ready

How to do it...

How it works...

There's more...

Restore files and folders

Getting ready

How to do it...

How it works...

There's more...

Backup and restore a Hyper-V Virtual Machine

Getting ready

How to do it...

How it works...

There's more...

Backup and perform bare metal recovery

Getting ready

How to do it...

How it works...

There's more...

Restore the registry from a backup

Getting ready

How to do it...

How it works...

There's more...

Create a daily backup report

Getting ready

How to do it...

How it works...

There's more...

Backup and restore using Microsoft Azure

Getting ready

How to do it...

How it works...

There's more...

Managing Performance

Introduction

Explore performance counters with Get-Counter

Getting ready

How to do it...

How it works...

There's more...

Explore performance counters using CIM cmdlets

Getting ready

How to do it...

How it works...

There's more...

Configuring and using Data Collector Sets

Getting ready

How to do it...

How it works...

There's more...

Reporting on performance data

Getting ready

How to do it...

How it works...

There's more...

Generating performance monitoring graph

Getting ready

How to do it...

How it works...

There's more...

Creating a system diagnostics report

Getting ready

How to do it...

How it works...

There's more...

Troubleshooting Windows Server 2016

Introduction

Checking network connectivity

Getting ready

How to do it...

How it works...

There's more...

Using troubleshooting packs

Getting ready

How to do it...

How it works...

There's more...

Use best practice analyzer

Getting ready

How to do it...

How it works...

There's more...

Managing event logs

Getting ready

How to do it...

How it works...

There's more...

Forward event logs to a central server

Getting ready

How to do it...

How it works...

There's more...

Managing Windows Networking Services

Introduction

New ways to do old things

Getting ready

How to do it...

How it works...

There's more...

Configuring IP addressing

Getting ready

How to do it...

How it works...

There's more...

Converting IP address from static to DHCP

Getting ready

How to do it...

How it works...

There's more...

Installing domain controllers and DNS

Getting ready

How to do it...

How it works...

There's more...

Configuring zones and resource records in DNS

Getting ready

How to do it...

How it works...

There's more...

Installing and authorizing a DHCP server

Getting ready

How to do it...

How it works...

There's more...

Configuring DHCP scopes

Getting ready

How to do it...

How it works...

There's more...

Configuring DHCP server failover and load balancing

Getting ready

How to do it...

How it works...

There's more...

Building a public key infrastructure

Getting ready

How to do it...

How it works...

There's more...

Creating and managing AD users, groups, and computers

Getting ready

How to do it...

How it works...

There's more...

Adding users to AD using a CSV file

Getting ready

How to do it...

How it works...

There's more...

Reporting on AD users

Getting ready

How to do it...

How it works...

There's more...

Finding expired computers in AD

Getting ready

How to do it...

How it works...

There's more...

Creating a privileged user report

Getting ready

How to do it...

How it works...

There's more...

Managing Network Shares

Introduction

Securing your SMB file server

Getting ready

How to do it...

How it works...

There's more...

Creating and securing SMB shares

Getting ready

How to do it...

How it works...

There's more...

Accessing SMB shares

Getting ready

How to do it...

How it works...

There's more...

Creating an iSCSI target

Getting ready

How to do it...

How it works...

There's more...

Using an iSCSI target

Getting ready

How to do it...

How it works...

There's more...

Creating a scale-out SMB file server

Getting ready

How to do it...

How it works...

There's more...

Configuring a DFS Namespace

Getting ready

How to do it...

How it works...

There's more...

Configuring DFS Replication

Getting Ready

How to do it...

How it works...

There's more...

Managing Internet Information Server

Introduction

Installing IIS

Getting ready

How to do it...

How it works...

There's more...

Configuring IIS for SSL

Getting ready

How to do it...

How it works...

There's more...

Managing TLS cipher suites

Getting ready

How to do it...

How it works...

There's more...

Configuring a central certificate store

Getting ready

How to do it...

How it works...

Configuring IIS bindings

Getting ready

How to do it...

How it works...

There's more ...

Configuring IIS logging and log files

Getting ready

How to do it...

How it works...

There's more...

Managing applications and application pools

Getting ready

How to do it...

How it works...

There's more...

Managing and monitoring network load balancing

Getting ready

How to do it...

How it works...

There's more...

Managing Hyper-V

Introduction

Installing and configuring Hyper-V feature

Getting ready

How to do it...

How it works...

There's more...

Using Windows PowerShell Direct

Getting ready

How to do it...

How it works...

There's more...

Securing Hyper-V host

Getting ready

How to do it...

How it works...

There's more...

Create a virtual machine

Getting ready

How to do it...

How it works...

There's more...

Configuring VM hardware

Getting ready

How to do it...

How it works...

There's more...

Configuring Hyper-V networking

Getting ready

How to do it...

How it works...

There's more...

Implementing nested Hyper-V

Getting ready

How to do it...

How it works...

There's more...

Managing VM state

Getting ready

How to do it...

How it works...

There's more...

Configuring VM and storage movement

Getting ready

How to do it...

How it works...

There's more...

Configuring VM replication

Getting ready

How to do it...

How it works...

There's more...

Managing VM checkpoints

Getting ready

How to do it...

How it works...

There's more...

Monitoring Hyper-V utilization and performance

Getting ready

How to do it...

How it works...

There's more...

Creating a Hyper-V health report

Getting ready

How to do it...

How it works...

There's more...

Managing Azure

Introduction

Using PowerShell with Azure

Getting ready

How to do it...

How it works...

There's more...

Creating Core Azure Resources

Getting Ready

How to do it...

How it works...

There's more...

Exploring your storage account

Getting ready

How to do it...

How it works...

There's more...

Creating Azure an SMB File Share

Getting ready

How to do it...

How it works...

There's more...

Creating and using websites

Getting ready

How to do it...

How it works...

There's more...

Creating and using Azure virtual machines

Getting ready

How to do it...

How it works...

There's more...

Using Desired State Configuration

Introduction

Using DSC and built-in resources

Getting ready

How to do it...

How it works...

There's more...

Parameterizing DSC configuration

Getting ready

How to do it...

How it works...

There's more...

Finding and installing DSC resources

Getting ready

How to do it...

How it works...

There's more...

Using DSC with PSGallery resources

Getting ready

How to do it...

How it works...

There's more...

Configuring Local Configuration Manager

Getting ready

How to do it...

How it works...

There's more...

Implementing a SMB pull server

Getting ready

How to do it...

How it works...

There's more...

Implementing a DSC web-based pull server

Getting ready

How to do it...

How it works...

There's more...

Using DSC partial configurations

Getting ready

How to do it...

How it works...

There's more...

Preface

PowerShell was first introduced to the world at the Professional Developer's conference in Los Angles in 2003 by Jeffrey Snover. Code named Monad, it represented a complete revolution in management. A white paper written around that time, The Monad Manifesto(refer to http://www.jsnover.com/blog/2011/10/01/monad-manifesto/) remains an amazing analysis of the problem at the time of managing large number of Windows systems. A key takeaway—the GUI does not scale, whereas PowerShell does.

PowerShell has transformed managing of complex, network-based Windows infrastructure and increasingly non-Windows infrastructure. Knowledge of PowerShell and how to get the most from PowerShell is now obligatory for any IT Pro job—the adage being Learn PowerShell or learn Golf.

This book takes you through the use of PowerShell in a variety of scenarios using many of the rich set of features included in Windows Server 2016. This preface provides you with an introduction to what is in the book and some tips on how to get the most out of the content.

What this book covers

Chapter 1, What's New in PowerShell and Windows Server, looks at some of the key new features in Windows Server 2016 and in the latest version of PowerShell.

Chapter 2, Implementing Nano Server, shows you how to set up and use Nano Server—a new server installation option for Windows Server 2016. Nano Server provides a great platform for running roles with a vastly reduced attack and patch surface.

Chapter 3, Managing Windows Updates, helps you get to grips with managing updates via Windows Update. With the importance of keeping all your Windows servers fully patched, managing WSUS is a key take in almost any size organization.

Chapter 4, Managing Printers, shows you how to manage printers, printer queues, and printer drivers, including deploying printers via Group Policy. This chapter also looks at branch office printing.

Chapter 5, Managing Server Backup, examines the use of Windows Server Backup and covers both backup (and restore) via cmdlet and via the console application. Windows Server Backup is a nice feature you can use either on its own in a small organization or to augment an enterprise wide third-party service.

Chapter 6, Managing Performance, shows you how to measure and monitor the performance of a server. There are several recipes that demonstrate how to get specific performance measurements and how to create graphs of performance for further analysis.

Chapter 7, Troubleshooting Windows Server 2016, looks at a number of aspects of both reactive and proactive troubleshooting. This includes getting events from the event log and forwarding event logs to a central server. This chapter also looks at the Best Practice Analyzer features baked into Windows Server.

Chapter 8, Managing Windows networking services, looks at various aspects of networking. Networks are today central to almost every organization and this chapter looks at a variety of network-related tasks, including looking at new ways (with PowerShell) to do old things, setting up DNS, DHCP, and Active directory, as well as building a multi-tier certificate authority infrastructure.

Chapter 9, Managing Network Shares, looks at sharing data between systems, including building a scaled out clustered file server based on iSCSI and using the DFS Namespace and DFS Replication features of Windows Server.

Chapter 10, Managing Internet Information Server, shows you how to conduct a variety of IIS-related tasks, including IIS installation and configuration, setting up SSL and managing cipher suites, as well as configuring Network Load Balancing.

Chapter 11, Managing Hyper-V, demonstrates the use of Hyper-V. This chapter shows you how to build and deploy VMs with Hyper-V. This includes nested Hyper-V running a Hyper-V VM inside another Hyper-V VM (which is useful for a number of scenarios).

Chapter 12, Managing Azure, looks at managing IaaS resources in Azure using PowerShell. To test the recipes in this chapter, you need access to Azure. This chapter describes how to get a trial subscription.

Chapter 13, Using Desired State Configuration, shows how to use this important feature to ensure a server is setup correctly and continues to remain so. This covers setting up a pull server and configuring partial configurations.

What you need for this book

To get the most out of this book, you need to experiment with the code contained in the recipes. To avoid errors impacting live production servers, you should instead use virtualization to create a test lab, where mistakes do not cause any serious damage. This book uses a variety of servers within a single Reskit.Org domain containing multiple servers, and using an IP address block of 10.10.10/24 described in Getting the most from this book.

Ideally, you should have a Windows 10 or Windows Server 2016 host with virtualization capabilities and use a virtualization solution. If you have access to a cloud computing platform, then you could perform most of the recipies in cloud-hosted virtual machines although that has not been tested. You can use any virtualization.

The book was developed using Hyper-V and nested Hyper-V on Windows 10 Creator's Update and Windows Server 2016. More details of the servers are contained in the preface and each recipe.

Who this book is for

This book is aimed at IT Pros, including system administrators, system engineers, as well as architects and consultants who need to leverage PowerShell to simplify and automate their daily tasks.

Getting the most from this book

This book was written based on some assumptions and with some constraints. You will need to read this section to understand how I intended the book to be used and what I have assumed about you. This should help you to get the most from this book.

The first assumption I made in writing this book is that you know the basics of PowerShell. This is not a PowerShell tutorial. The recipes do make use of a wide range of PowerShell features, including WMI, Remoting, AD and so on, but you will need to know the basics of PowerShell. The book uses PowerShell language, syntax, and cmdlets that come with Windows Server 2016 and Windows 10 (CU).

The recipes provide the basics—you adopt and adapt. The recipes are designed to show you the basics of how to manage certain aspects of Windows Server 2016 using PowerShell (and in some cases Windows Console Applications). In many cases, a recipe stresses that you can improve it for your environment. The recipe is meant to show you how some features work, so you can leverage and extend it for your environment.

Start by running the recipes step by step. The recipes were built and tested step by step. Once you have it working, re-factor them into your own reusable functions. In some cases, we build simple functions as a guide to richer scripts you could build.

Writing PowerShell scripts for publication in a book is a layout nightmare. To get around this, I have made extensive use of the various ways in which you can create multiline commands within PowerShell. This involves using the back tick (`) line continuation as well as using the Pipe character at the end of the line. I also sometimes specify an array of values across multiple lines with a comma at the end of the continuing line. Hopefully, the screenshots more or less match up. So, read the text carefully and pay attention particularly to the back tick.

 

In all too many places and to save lots of extra blank space, code spills over a page break, or where a figure and related text are split across a page boundary. I hope there are not too many issues with layout!

Many of the cmdlet or object methods used in this book produce output that may not be all that helpful or useful. In some cases, the output generates a lot of pages of little value. For this reason, many recipes pipe to Out-Null. Feel free to remove this where you want to see more details. In some cases, I have adjusted the output to avoid wasted white space. Thus, if you test a recipe, you may see the output that is laid out a bit differently, but it should contain the same information. Of course, the specific output you see may be different based on your environment and the specific values you use in each step.

To write this book, I have used a large VM farm consisting of over 20 Windows 2016 servers and Windows 10 clients. All the hosts used in this book are a combination of some physical hardware (running almost entirely on Windows 10 Creators Update and a large set of VMs, including the following:

Domain Controllers (

DC1

,

 

DC2

)—also hosts DHCP Server, IIS, and other roles).

File Servers (

FS1

,

 

FS1

)

Network Load Balanced IIS servers (

NLB1

,

 

NLB2

)

Print Server (

PSrv

)

General purpose servers (

SRV1

,

 

SRV2

)

Client computers (

CL1

,

 

SG-BR

-

CL1

)

Certificate servers (

root

,

 

CA)

Hyper-V Servers (

HV1

,

 

HV1

), including an embedded VM,

 

VM1.

Each recipe notes the servers in use. Feel free to change things to suit your needs and based on your own naming conventions.

In building the VM farm, I have used an IP address block of

 

10.10.10.0/24

. The recipes show specific addresses in use, but you can adapt these to fit your environment. The IP addresses used are assigned as follows:

IP address

Server name

10.10.10.10

DC1 (DC, DHCP, DNS, IIS, and so on)

10.10.10.11

DC2 (DC, DHCP, and DNS)

10.10.10.20

Root (CA offline root)

10.10.10.21

CA.Reskit.Org—issuing CA

10.10.10.50

SRV1 (server with numerous roles)

10.10.10.51

10.10.10.55

SRV2 (server with numerous roles)

ReskitNLB (NLB Virtual Server)

10.10.10.60

PSRV (print server)

10.10.10.61

Sales.Reskit.Org—a network printer

10.10.10.62

Sales2.reskit.org—a printer at as remote office

10.10.10.100

FS.Reskit.Org (Cluster address)

10.10.10.101/102

FS1 (file server cluster node—with 2 nics)

10.10.10.105/106

FS2 (file server cluster node—with w nics)

10.10.10.131

Nano1

10.10.10.132

Nano2

10.10.10.141

SG-CL1 (client computer in the Sales Group)

10.10.10.146

SG-BR-CL1 (sales group branch office client)

10.10.10.201

HV1 (Hyper-V server)

10.10.10.202

HV2 (Hyper-V server)

10.10.10.251

WSUS1 (WSUS Server)

10.10.10.254

Default gateway

 

The full set of VMs, at the end of this writing, took up around 725 GB of storage. Fortunately, storage is cheap!

PowerShell provides great feature coverage—you can manage most of the functions and features of Windows Server 2016 using PowerShell, but by no means all. In some cases, you can dip down into WMI using the CIM cmdlets to get to object properties and methods not exposed by any cmdlet. The advent of CDXML-based cmdlets has increased the number of networking and other cmdlets that are WMI-based. But even then, there are still a number of places where you need to use a Windows console application or invoke an unmanaged DLL. The bottom line is that to manage some aspects of Windows, such as event forwarding or performance logging, you will need to use older tools. We try to avoid these, but in many cases the recipe demonstrates how to use the console applications within PowerShell.

I have avoided where possible using external, third-party modules and have focused on what comes in the box. But, in some cases, such as Azure, you have to add code and in other cases such as DSC you benefit greatly from third-party code. The book shows that there is a wealth of tools, add-ins, and tips/tricks that you can leverage (even if we do not use all that much of it). One thing to keep in mind, integrating various add-ons (and keeping them up to date and working well) can be a challenge.

All the code provided in this book has been tested; it worked and did what it says (at least during the writing stage). The production process is complex and it's possible that errors in code creep in during the production stages. Some of the more complex steps may have errors introduced during production. If any step fails for you, please contact PACKT and we'll help. Feel free to post issues to the Spiceworks PowerShell forum for quick resolution.

In writing this book, we set out to create content around a number of features of Windows Server 2016. As the book progressed, we quickly hit (and broke) several content limits. In order to publish the book, it was necessary to remove some content, which we did most reluctantly. Coverage of Storage and Containers had to be dropped. To paraphrase Jeffrey Snover,

 

To ship is to choose. I hope I chose well

.

In writing the recipes, we use full cmdlet names with no aliases and with all parameter names spelled out in full (so, this means no abbreviated parameter names or positional parameters). This makes the text a bit longer, but hopefully easier to read and understand.

Some recipes in this book rely on other recipes being completed.

 

These related recipes worked well when we wrote them and hopefully will work for you as well. Each depending recipe is noted.

There is a fine line between PowerShell and a Windows feature. To use PowerShell to manage a Windows feature, you need to understand the feature itself. The chapters describe each feature although in the space limited, thus I can't provide complete details of every feature. I have provided links to help you get more information. And as ever, Bing and Google are your friends.

Sections

In this book, you find several headings that appear frequently (Getting ready, How to do it, How it works, There's more).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Chapter and Recipe Headings

Every chapter and every recipe introduces some part of Windows which the recipes help you to manage. I've attempted to summarize the key points about each feature - but as ever there is more detail you can discover using your favorite search engine.

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe. It also indicates the hosts (VMs) you need for the recipe and any files, folders, or other resources you need to complete the recipe successfully.

How to do it...

This section contains the steps required to follow the recipe. We show the PowerShell code you use to perform each step

How it works...

This section contains a detailed explanation of what happened in the previous section along with screen shots to show you the results of the recipe.

There's more...

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

Conventions

In this book, you find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, URLs, and so on are shown as follows:

"A great PowerShell cmdlet is Get-Help"

A block of code is set as follows:

If (-Not (Get-WindowsFeature -Name PowerShell)) { 'PowerShell Not installed' }

Any command-line input or output is written as follows (Note the back tick at the end of the second line):

# Copy ISO image

Copy-Item -Path c:\Image\Server2016.iSO `

-TargetPath c:\VM\ISO\Server2016.ISO

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you can really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/WindowsServer2016AutomationwithPowerShellCookbookSecondEdition_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in this book-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission is accepted and the errata uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information appears under the Errata section.

If you find issues, feel free to reach out to the author via the Spiceworks forum.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we do our best to address the problem.

Help and assistance

If you want help on any of the recipes, or want to discover more information about any of the steps, come over to the PowerShell forum at Spiceworks. Navigate to: https://community.spiceworks.com/programming/powershell and ask away. Note you do need to register to be able to ask questions and participate.

 

What's New in PowerShell and Windows Server

 This chapter covers the following recipes:

Exploring Remote Server Administration Tools (RSAT)

Discovering new cmdlets in PowerShell 4 and Windows Server 2012 R2

Discovering new cmdlets in PowerShell 5/5.1 and Windows Server 2016

Exploring PowerShellGet

Exploring PackageManagement

Creating an internal PowerShell repository

Introduction

Windows Server changes quickly, with a new release about every two years. Since the publication of the last edition of this book, Microsoft has delivered both Windows Server 2012 R2 and Windows Server 2016 (as well as client OS versions: Windows 8.1 and Windows 10).

PowerShell evolved alongside the server OS with a release of both PowerShell version 4, version 5, and version 5.1. This chapter reviews the changes in both the OS and PowerShell and highlights the biggest and most useful changes and new cmdlets.

This chapter also explores PowerShellGet and PackageManagement modules, perhaps the most interesting and useful new features released in PowerShell 5 and PowerShell 5.1.

Exploring Remote Server Administration Tools (RSAT)

Remote Server Administration Tools (RSAT) are tools available on both servers and client systems to manage server services. RSAT tools are available in Windows desktop and server versions. Most of the RSAT tools are not installed by default but are easily added.

RSAT includes GUI tools, like Microsoft Management Console (MMC) and MMC snap-ins (for example the DNS or DHCP MMC snap-ins) as well as command-line tools and additional PowerShell modules. You have the option of installing the Windows feature including the tools (most useful on a server), or just the tools to manage the feature (most useful on a workstation).

The recipe that follows is run from DC1, a Windows Server 2016 with Desktop Experience installation. If you try to use Server Core for this recipe, note that Out-GridView, for example in step 3, is not available in the Server Core version, as it lacks the graphical user interface. For Server Core installations, use Format-Table instead.)

How it works...

In step 1, you use Get-Command to enumerate all the commands available in PowerShell. This includes functions and aliases. It is useful to store the result of such commands into a variable, $CommandsBeforeRSAT in this case, so you are able to investigate the commands without making the request again. Using Tee-Object, you store the array of commands in that variable while continuing to use the pipeline to Measure-Object to store the count of commands, then display the result using the PowerShell string formatting function: '{0} commands' -f $CountOfCommandsBeforeRSAT

In step 2, you pipe the $CommandsBeforeRSAT variable to Get-Member to examine the TypeName of the objects returned, as shown in the following screenshot:

As you see, these commands are objects of the AliasInfo, FunctionInfo, and CmdletInfo types in the System.Management.Automation namespace (plus a FilterInfo type, which provides information about a filter that is stored in the session state.) PowerShell commands returned by Get-Command include aliases, functions, and cmdlets.

In step 3, you use Select-Object to show the useful properties, and pipe that to a Sort-Object, then pipe to Out-GridView to search and filter the PowerShell commands, as you see in the following screenshot:

In step 4, you use Get-Module just like Get-Command, but use the -ListAvailable parameter to see all the installed modules, not just those loaded into the current session. Again you use Tee-Object to store the array of modules into a variable, $ModulesBeforeRSAT, while passing the result down the pipeline to Measure-Object to calculate the count which you then display.

In step 5, you pipe the variable to a Select-Object for the interesting columns, Sort-Object, then pipe that to Out-GridView again to review the available modules as shown here:

In step 6, you view the RSAT features available in your server with Get-WindowsFeature -Name RSAT*, as shown in the following screenshot:

Get-WindowsFeature presents an information dense tree view of the RSAT tools available. Note the many sub-features under Remote Server Admin Tools and under Role Administration Tools. Each feature may be installed individually by name, or all features installed with one command as in this example.

In step 7, install all the RSAT features with the -IncludeAllSubFeature and-IncludeManagementTools parameters. You may limit what is installed by changing the first parameter to a comma separated list of desired feature names.

In steps 8-11, once the RSAT features are installed, repeat the Get-Command and Get-Modules code to see all the additional cmdlets and modules.

In step 12 you use Export-CliXML to store the array to an XML file. If you want to compare what is available in different OS and PowerShell versions, you use the array of objects saved to this file and compare it with an XML file generated under some other PowerShell or Windows versions.

There's more...

Jose Barreto, a Principal Program Manager, Applications and Services Group at Microsoft, reviewed the new Windows Server 2016 cmdlets (based on Windows Server 2016 CTP). This post shows you how to use Export-CliXML to see what has changed between PowerShell versions:

https://blogs.technet.microsoft.com/josebda/2015/05/26/new-powershell-cmdlets-in-windows-server-2016-tp2-compared-to-windows-server-2012-r2/.

Discovering new cmdlets in PowerShell 4 and Windows Server 2012 R2

PowerShell V4 and Server 2012 R2 added many new features to existing cmdlets but did not add many new cmdlets. A notable exception is Desired State Configuration (DSC) feature that debuted in PowerShell V4.

DSC is a set of language extensions that enable you to define computer configurations in a declarative fashion then apply that configuration to managed computers. DSC is a tool to provision or manage servers and to ensure those systems stay configured correctly. DSC provides a solution to the problem of configuration drift—computer configurations that change, often incorrectly, over time.

Get more information on DSC in Chapter 13, Using Desired State Configuration.

New cmdlets

Two other useful cmdlets included in PowerShell V4 are:

Get-FileHash

: Creates a hash value from a given file or binary value. This is useful for quickly determining whether files have changed or for finding duplicate files (that have different file names)

Test-NetConnection

: Diagnoses a network connection and provides helpful troubleshooting information. This cmdlet is described in more detail in

Chapter 8

,

Managing Windows Network Services

.

How to do it...

You use the

Show-Command

to investigate the

Get-FileHash

cmdlet:

Show-Command -Name Get-FileHash

Show0-Command is not available in the Server Core version, as it lacks the graphical user interface.

In the dialog that pops up, the

Path

tab corresponds to one of three parameter sets for this command. For the

Path

tab, enter

$Env:windirnotepad.exe

or any other valid file path.

Choose an algorithm like

SHA512

from the drop-down menu.

Click the

Copy

button then paste the command into your PowerShell ISE and press

Enter

to run it. Note the hash value that is returned.

Use

Show-Command

to investigate

Test-NetConnection

:

Show-Command -Name Test-NetConnection

In the dialog box, the

CommonTCPPort

tab corresponds to the default parameter set, the first of four. Choose

HTTP

from the

CommonTCPPort

drop-down, and choose

Detailed

for

InformationLevel

. Then click

Copy

, and paste the script into your editor below the

Show-Command

line, then close the

Show-Command

window. Select this line and press

F8

to run this line.

Repeat your call to

Show-Command -Name Test-NetConnection

. Choose the

ICMP

tab and enter a valid internet hostname like

Windows.Com

in the

ComputerName

field, or leave it blank, and choose

Detailed

for

InformationLevel

.

Click the

Copy

button then paste the command into your PowerShell ISE below the previous command, then close the

Show-Command

window and select the line and press

F8

to run it.

Repeat your call to

Show-Command Name Test-NetConnection

. Choose the

NetRouteDiagnostics

tab, check the box for

DiagnoseRouting

, and click

Run

.

Repeat your call to

Show-Command -Name Test-NetConnection

. Choose the

RemotePort

tab, enter

443

for the

Port

, and choose

Detailed

for

InformationLevel

, and click

Run

.

How it works...

In step 1, you use Show-Command to provide a graphical interface to explore new commands like Get-FileHash or new ways to use commands you know. It is the same interface that displays in the Commands tab in PowerShell ISE, and the interface is programmatically generated from the parameter definitions in the cmdlet or function, so it works with commands you create or install from outside sources.

In steps 2 and 3, choosing the Path tab corresponds to a parameter set defined in the command; each parameter set may have different required and optional parameters, represented by check boxes, drop-down menus, or text fields. This parameter set requires the Path and Algorithm parameters.

In step 4, the Copy button puts a syntax-correct command on our clipboard, either to be run as is or added to a script and modified. This is a very useful feature for new PowerShell scripters or those working with unfamiliar commands. The result of the command displays in the console, but it could be stored into a variable for comparison with other hash values to look for duplicate or changed files:

In steps 5 and 6, you use Show-Command to explore the Test-NetConnection cmdlet. This is a flexible and useful troubleshooting command with four parameter sets to use. First, test the connection to a web host over HTTP port 80. Note the -InformationLevel Detailed parameter provides additional troubleshooting information on the connectivity.

In steps 7 and 8, you use the ICMP parameter set with the -InformationLevel Detailed parameter to ping, using ICMP echo request, a web server. This is different to the earlier steps—here you are just determining whether the target server is responding to echo requests. Some web servers turn off returning of pings, so you may see a server that doesn't respond to a ping but does allow a port 80 HTTP connection.

In step 9, you use the NetRouteDiagnostics parameter set with the -DiagnoseRouting parameter, which was introduced in PowerShell 5.1, to get routing information. Here when you click the Run button, the result displays in the console window.

In step 10, you specify a RemotePort parameter set with a specified Port and ComputerName to test:

There's more...

Both Server 2012 R2 and PowerShell V4 introduced many new features and added enhancements to existing features. This included the Hyper-V, SmbShare, and BranchCache features, all of which were improved. These features came with PowerShell modules that enable you to leverage these features using PowerShell. Get more information on the modules that support the 2012 R2 features at https://technet.microsoft.com/en-us/library/dn249523.aspx.

Discovering new cmdlets in PowerShell 5/5.1 and Windows Server 2016

PowerShell V5, PowerShell V5.1, and Windows Server 2016 also added new features.

Getting ready

Run the commands in the following recipe on a Windows Server 2016 with Desktop Experience version.

PowerShellGet module

PowerShellGet, formerly known as OneGet, is a module that provides you with a simple way to discover, install, and update PowerShell modules and scripts. It has dependencies on the PackageManagement module, which relies on NuGet. It is an open source project, located at https://github.com/powershell/powershellget.

Refer to Explore PowerShellGet recipe.

PackageManagement module

The cmdlets in the PackageManagement module provide a single interface for software publication, discovery, installation, and inventory.

Refer to the following recipe:

Explore PackageManagement

Create a PackageManagement repository

Microsoft.PowerShell.Archive module

The Microsoft.Powershell.Archive module contains two useful functions: Compress-Archive and Expand-Archive. These enable you to create and extract ZIP files. With previous versions of PowerShell versions, you managed archives by using the System.IO.Compression namespace from the .Net framework, the Shell.Application com object or software like 7-Zip.

Microsoft.PowerShell.Utility module

The Microsoft.PowerShell.Utility module contains several new cmdlets useful for debugging interactively and within runspaces.

Debugging and runspace Cmdlets include: Get-Runspace, Debug-Runspace, Get-RunspaceDebug, Enable-RunspaceDebug, and Disable-RunspaceDebug, Wait-Debugger, Debug-Job.

These cmdlets enable debugging PowerShell scripts within runspaces and jobs and add additional debugging features for debugging production PowerShell interactively.

Other new modules

Other new modules in this version of PowerShell (and where to find more information about each module) include:

Module

Description

Documentation

ConfigCI

Manage the configurable code integrity policy for Windows

https://technet.microsoft.com/en-us/library/mt634481.aspx

Defender

Manage Windows defender

https://technet.microsoft.com/en-us/library/dn433280.aspx

EventTracingManagement

Manage event tracing for Windows providers and sessions

https://technet.microsoft.com/en-us/library/dn919247.aspx

HgsClient, ShieldedVMDataFile, and ShieldedVMTemplate

Manage the host guardian service, for shielded Hyper-V guest machines.

https://technet.microsoft.com/en-us/library/dn914505.aspxhttps://technet.microsoft.com/en-us/library/mt791280.aspxhttps://technet.microsoft.com/en-us/library/mt282520.aspx

IISAdministration

Manage IIS replaces WebAdministration cmdlets

https://technet.microsoft.com/en-us/library/mt270166.aspx

NetworkController

Manage the new network controller role in Server 2016

https://technet.microsoft.com/en-us/library/dn859239.aspx

NetworkSwitchManager

Manage supported network switches in Server 2016

https://technet.microsoft.com/en-us/library/mt171434.aspx

Pester

Manage unit tests for PowerShell modules and cmdlets

https://github.com/pester/Pester/wiki

PnpDevice

Cmdlets for managing plug and play devices

https://technet.microsoft.com/en-us/library/mt130251.aspx

StorageQoS and StorageReplica

Support new storage functionality in Server 2016.

https://technet.microsoft.com/en-us/library/mt608557.aspxhttps://technet.microsoft.com/en-us/library/mt744543.aspx

Other new cmdlets

Some other useful cmdlets included are:

Write-Information

: A replacement for the

Write-Host

cmdlet that is consistent with the other

Write-*

cmdlets in the

Microsoft.PowerShell.Utility

namespace. See

https://blogs.technet.microsoft.com/heyscriptingguy/2015/07/04/weekend-scripter-welcome-to-the-powershell-information-stream/

.

ConvertFrom-String

and 

Convert-String

: The new string parsing functions that create structured data from strings, or parse out string data into structured data. See

https://blogs.msdn.microsoft.com/powershell/2014/10/31/convertfrom-string-example-based-text-parsing/

.

Format-Hex

: This cmdlet formats information into hexadecimal.

Get-Clipboard

and 

Set-Clipboard

: A cmdlet to simplify working with the clipboard, replacing piping to

clip.exe

.

Clear-RecycleBin

: This cmdlet empties the

Recycle Bin

.

New-TemporaryFile

: Simplifies the creation of temporary files within PowerShell scripts.

New-Guid

: A wrapper for

[GUID]::NewGuid()

to simplify the creation of

Globally Unique Identifiers

(

GUIDs

). A GUID is an identifier, unique in space and time, that you use in a variety of scenarios.

System Center Virtual Machine Manager

, for example, uses GUIDs in jobs created by the UI.

Enter-PSHostProcess

and 

Exit-PSHostProcess

: These enable you to debug PowerShell processes outside the current host process.

Export-ODataEndpointProxy

: This cmdlet generates a wrapper module for working with an OData endpoint. See

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.odatautils/microsoft.powershell.odatautils

.

Explore some of these cmdlets here and in later chapters as well.

How it works...

In step 1, you get the commands with the Write verb in the Microsoft.PowerShell.Utility module. Write-Information is an addition to this module that writes out to a new information stream, which the about_Redirection help topic describes in detail:

In steps 2-5, note that messages from Write-Information are not displayed by default. The $InformationPreference variable controls this behaviour within your PowerShell session.

In step 6, you'll see the CommonParameters now include InformationAction and InformationVariable

More information is available in Get-Help about_CommonParameters:

In step 7 you create a PSCustomObject using ConvertFrom-String with NoteProperties named P1, P2, P3, and P4 that correspond to words separated by whitespace from the input text, with string or char data types:

In step 8, you control the names of the NoteProperties. In step 9 you change the delimiter from the default of whitespace to a comma, thus parsing a comma separated list:

In step 10, you investigate the -TemplateObject parameter to parse inconsistently formatted data. Here you provide one or more patterns by example in the TemplateObject and provide the template along with the text to parse. The template starts with one line as an example, and initially recognizes only one line out of four in the text to match:

In steps 11 and steps 12, you improve the template with each attempt, achieving complete matching results from the Convert-FromString:

In step 13, you use Format-Hex on a here string that contains two lines of text. Note the 0D 0A bytes corresponding to carriage return and line feed (CRLF) between lines:

In step 14 and step 15, you work with Set-Clipboard and Get-Clipboard. By copying any text with Ctrl+C, you then capture that value into a variable with Get-Clipboard. You use Set-Clipboard to change that value, and use Ctrl+V to verify the change.

There's more...

Each PowerShell release comes with release notes that dive into the details of changes introduced with that version. These pages are updated with community contributions, as PowerShell is now partially open source: