Mastering windows powershell scripting pdf

Mastering Windows PowerShell Scripting

Описание

If you are a system administrator who wants to become an expert in controlling and automating your Windows environment, then this book is for you. Prior knowledge of PowerShell’s core elements and applications is required for this book.

Об авторе

Похожие авторы

Связанные категории

Предварительный просмотр книги

Mastering Windows PowerShell Scripting — Brenton J.W. Blawat

Table of Contents

Mastering Windows PowerShell Scripting

Credits

Foreword

About the Author

About the Reviewers

www.PacktPub.com

Support files, eBooks, discount offers, and more

Why subscribe?

Free access for Packt account holders

Instant updates on new Packt books

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

1. Variables, Arrays, and Hashes

Variables

Objects stored in variables

Arrays

Single-dimension arrays

Jagged arrays

Updating array values

Hashes

Deciding the best container for your scripts

Summary

2. Data Parsing and Manipulation

String manipulation

Replacing and splitting strings

Counting and trimming strings

The Trim method

The Substring method

The string true and false methods

Number manipulation and parsing

Formatting numbers

Formatting bytes

Date and time manipulation

Forcing data types

Piping variables

Summary

3. Comparison Operators

Comparison operator basics

Equal and not equal comparison

Greater than and less than comparison

Contains, like, and match operators

And / OR comparison operators

Best practices for comparison operators

Summary

4. Functions, Switches, and Loops Structures

Functions

Looping structures

Switches

Combining the use of functions, switches, and loops

Best practices for functions, switches, and loops

Best practices for functions

Best practices for looping structures and switches

Summary

5. Regular Expressions

Getting started with regular expressions

Regular expression grouping constructs and ranges

Regular expression quantifiers

Regular expression anchors

Regular expressions examples

Summary

6. Error and Exception Handling and Testing Code

Error and exception handling – parameters

Error and exception handling – Try/Catch

Error and exception handling –Try/Catch with parameters

Error and exception handling – legacy exception handling

Methodologies for testing code

Testing the –WhatIf argument

Testing the frequency

Hit testing containers

Don’t test in production

Summary

7. Session-based Remote Management

Utilizing CIM sessions

Creating a session

Creating a session with session options

Using sessions for remote management

Removing sessions

Summary

8. Managing Files, Folders, and Registry Items

Registry provider

Creating files, folders, and registry items with PowerShell

Adding named values to registry keys

Verifying files, folders, and registry items

Copying and moving files and folders

Renaming files, folders, registry keys, and named values

Deleting files, folders, registry keys, and named values

Summary

9. File, Folder, and Registry Attributes, ACLs, and Properties

Retrieving attributes and properties

Viewing file and folder extended attributes

Setting the mode and extended file and folder attributes

Managing file, folder, and registry permissions

Copying access control lists

Adding and removing ACL rules

Summary

10. Windows Management Instrumentation

WMI structure

Using WMI objects

Searching for WMI classes

Creating, modifying, and removing WMI property instances

Creating property instances

Modifying property instances

Removing property instances

Invoking WMI class methods

Summary

11. XML Manipulation

XML file structure

Reading XML files

Adding XML content

Modifying XML content

Removing XML content

Summary

12. Managing Microsoft Systems with PowerShell

Managing local users and groups

Managing local users

Managing local groups

Querying for local users and groups

Managing Windows services

Managing Windows processes

Installing Windows features and roles

Summary

13. Automation of the Environment

Invoking programs for automation

Using desired state configuration

Authoring phase

Staging and remediation phase

Detecting and restoring drifting configurations

Summary

14. Script Creation Best Practices and Conclusion

Best practices for script management

# commenting headers

Commenting code

Best practices for script creation

Script structure

Other important best practices for script creation

Controlling source files

Best practices for software automation

Summary

Mastering Windows PowerShell Scripting – conclusion

Staying connected with the author

Index

Mastering Windows PowerShell Scripting

Mastering Windows PowerShell Scripting

Copyright © 2015 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: April 2015

Production reference: 1210415

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78217-355-7

www.packtpub.com

Credits

Author

Brenton J.W. Blawat

Reviewers

Tim Amico

Christophe CRÉMON

Tomas Restrepo

Acquisition Editor

Meeta Rajani

Content Development Editor

Rohit Singh

Technical Editor

Tanvi Bhatt

Copy Editors

Hiral Bhat

Sonia Mathur

Vikrant Phadke

Alpha Singh

Project Coordinator

Mary Alex

Proofreaders

Simran Bhogal

Safis Editing

Maria Gould

Читайте также:  Осталось 1001 активация windows

Paul Hindle

Indexer

Rekha Nair

Production Coordinator

Alwin Roy

Cover Work

Alwin Roy

Foreword

We all appreciate a little simplicity when it enters our busy, complicated lives. Technology is no different. In fact, that is what we expect from technology—it should simplify our lives. But it doesn’t always work that way.

Sometimes technology can introduce vexing problems we don’t anticipate.

With every version of Microsoft DOS and then Windows, Microsoft included separate command-line interface shells. The shell could automate some tasks, but not all of them. Some tasks had to be accomplished manually, which is antithetical—nearly heretical—to our understanding of technology’s role.

What should have been simple, automated tasks became slow, frustrating, and manual chores. That conundrum didn’t go unnoticed.

Microsoft provided much-needed simplicity when it introduced PowerShell in 2006. Task automation and configuration management eliminated a great deal of time-consuming manual work. In short, PowerShell was a game changer.

PowerShell has solved many of the command-line and scripting issues that complicated our work. It introduced simplicity. It helped organizations become more agile, more productive, and save money. PowerShell is a powerful tool, and it has demonstrated its practical value many times.

Despite its utility, though, PowerShell remains a confusing tool to many IT administrators, and the need for greater clarity remains.

It is through this lens that Mr. Brenton Blawat provides an insightful new analysis of PowerShell—a valuable guidebook for those who struggle to understand PowerShell. Others have offered narratives that attempt to explain PowerShell, but they rarely provide the roadmap, background, or context that administrators need to get from Point A to Point B.

So, this is the right time for a comprehensive new analysis.

In general terms, Mr. Blawat’s book will help those who struggle to manage their compute environments. It includes important guidance on programming in PowerShell, starting with basic concepts and then introducing advanced configurations.

Mr. Blawat deconstructs and demystifies this programming language, sharing his intimate knowledge in a format that demonstrates the clarity of thought and prose that a difficult subject requires. Many authors have attempted this climb, but only Mr. Blawat has reached the summit. His examination provides relevant information for administrators who work with—and sometimes struggle with—PowerShell on a daily basis.

As Mr. Blawat explains in the following pages, the rapid adoption of cloud-based technologies paralleled the never-ending need for additional computing power in data centers. This created the need to efficiently build and expand systems with extreme precision. In addition to provisioning the base systems, there was a need to dynamically customize these new systems to work in unison with current running environments.

This drove the need for the next generation system automation languages that would provide full configuration for systems on the fly. Not only do these automation languages greatly reduce time to use, but they also ensure that no mistakes are made during the configuration process. All systems are created equally.

PowerShell is a .NET-based next generation automation language that provides both systems provisioning and management functionality for Windows-based systems. Leveraging command-line like interactions, PowerShell can be compiled into scripts that can systematically execute tasks on a system. Not limited to creating new systems, engineers are leveraging PowerShell to automate mundane tasks so that they can focus on other pressing activities in their environments.

Microsoft has fully embraced PowerShell in its full software portfolio to offer full integration with its products. Not only can you dynamically install the Microsoft software, but you can also fully manage the entire Microsoft software environment using PowerShell. PowerShell has also been embraced by third-party manufacturers through the integration of PowerShell modules. These modules provide full management capabilities for products such as network devices, storage subsystems, virtualization guests and hosts, security appliances, and other third-party applications.

Like many organizations, CDW has benefitted greatly from PowerShell, so this book hits very close to home for me. We use PowerShell scripts to manage customer environments in managed services and the installation of management tools.

We use Microsoft Orchestrator to provide back-end logic for simple user interfaces for help desk activities, like user-driven password resets and user-driven software installations. We also rely on Microsoft Orchestrator to automatically troubleshoot and remediate systems.

CDW’s customers also benefit from PowerShell in myriad ways. We assist a wide variety of Fortune 500 clients to develop PowerShell automation scripts to build new systems and manage their environments, including health check scripts, systems discovery, and advanced regulatory security analysis.

Clearly, PowerShell’s incredible utility has made it invaluable to CDW, our customers, and countless organizations across the globe. But understanding all of its many facets represents a daunting task. Organizations are unable to leverage PowerShell if they don’t fully understand its potential.

That’s where Mr. Blawat excels.

Mr. Blawat’s comprehensive new work will serve as a reference tool for engineers who work with Windows by taking the mystery out of common tasks that aren’t easily understood and aren’t always intuitive. Diligent readers will no doubt find many more reasons to give Mr. Blawat’s thorough narrative a prominent place on their bookshelves.

As Mr. Blawat’s coworker, I also feel proud that he is sharing his knowledge with the world—not only so others can benefit from his experience, but so they can see what those of us who work with him at CDW witness on a daily basis.

PowerShell has proven to be an incredibly useful tool for IT administrators since it burst on to the scene. Now there is a book about PowerShell that will prove equally useful.

Jon Stevens

Chief Information Officer

CDW

About the Author

Brenton J.W. Blawat is an entrepreneur, strategic technical advisor, author, and senior consultant, who has a passion for the procurement of technology in profit-based organizations. He is business-centric and technology-minded. Brenton has many years of experience in bridging the gap between technical staff and decision-makers in several organizations. He takes pride in his ability to effectively communicate with a diverse audience and provide strategic direction for large and small organizations alike.

Читайте также:  Как кидать курсоры для windows

In 2013, Brenton authored his first book, PowerShell 3.0 WMI Starter, Packt Publishing. This book was designed to be a starter for those interested in manipulating Windows Management Instrumentation through the use of PowerShell 3.0. This book is available in all popular book stores, including Packt Publishing’s website, http://bit.ly/18pcpGK.

Brenton currently works at CDW as a senior consulting engineer in strategic solutions and services. CDW is a leading multibrand technology solutions provider in the fields of business, government, education, and healthcare. A Fortune 500 company, it was founded in 1984 and employs approximately 7,200 coworkers. In 2014, the company generated net sales of more than $12.0 billion. For more information about CDW, you can visit www.CDW.com.

I would like to thank the foreword coordination team, Mary Viola, Scott Thomas, Jimmy Thomson, Brandon King, Sondra Ragusin, Meredith Braselman, and Bill Glanz. I would like to dedicate this book to my beautiful nieces, Caliett and Evie.

About the Reviewers

Tim Amico is a consulting engineer at CDW, who specializes in Configuration Manager and Operating System Deployment. He started his career in IT back in 1998, when he worked as a configuration tech for CompuCom, learning about what is required to become an IT professional. Since then, he has climbed the ladder from hardware field support and software deployment support to his current role (for the last 10 years) as an IT consultant, designing and implementing endpoint and mobility management solutions. Apart from Configuration Manager and OSD, Tim also has experience in PowerShell, BitLocker drive encryption deployments, Intel vPro provisioning and use case design, Active Directory (both in Azure and Windows Server), SQL design and reporting, PKI design, and Microsoft Intune.

Christophe CRÉMON is a SharePoint infrastructure architect, with 10 years of experience in information technology, especially Microsoft. He has been using PowerShell since 2008, and has published useful scripts and modules for IT Administrators at powershell.codeplex.com. He has a personal website at www.christophecremon.com.

Tomas Restrepo has been writing software for over 10 years, starting with C/C++ and eventually moving to the .NET platform. He currently spends most of his time helping other developers solve complex problems and troubleshooting application performance and scalability issues.

www.PacktPub.com

Support files, eBooks, discount offers, and more

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.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at 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://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can search, access, and read Packt’s entire library of books.

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

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Instant updates on new Packt books

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.

Preface

PowerShell is a network scripting language that provides a set of tools to administer Microsoft products. While PowerShell is based on command-line interactions, it is much more powerful than what the standard command line offers. It has built-in sections of code called cmdlets. They simplify functions that you may need to perform on a system. Using cmdlets greatly reduces the number of lines of code that are required to perform actions, compared to other scripting languages, such as VBScript.

PowerShell is based on the verb-noun naming convention, which allows scripters to declare an action followed by an object to configure. For example, the get-service cmdlet easily designates that you are getting a Windows service. This literal naming convention helps readers quickly learn how to program in PowerShell, as the actions are easily remembered.

Community support for PowerShell has grown astronomically. Not only have large companies adopted PowerShell in their environments, but universities are also regularly teaching PowerShell courses to their students. PowerShell’s feature set keeps growing with every release of the product. It is conceivable in the near future that you will be able to fully automate the configuration of every component in a data center. This will remove the needs of multiple engineering specialists to provision networking, storage, firewalls, operating systems builds, and high-availability configurations. It will all be done via PowerShell scripting and the systems will be able to be configured using a singular network language.

This book provides a strong foundation for learning PowerShell using real-world scenarios. You will not only be able to quickly learn how to program in this language, but also be able to produce scripts that you can use in your existing environments. This book will also be a great reference book for you to look back on and revisit as you are coding. It will provide the proper syntax and show you successful ways to implement your code. When you are done with reading this book, you will be well on your way to mastering PowerShell !

Читайте также:  Xcode mac os что это такое

What this book covers

Chapter 1, Variables, Arrays, and Hashes, explores the different data and object containers that you can use in PowerShell. These containers include variables, arrays, and hashes. This chapter provides examples on how to use these containers to store objects.

Chapter 2, Data Parsing and Manipulation, dives into the different data types and how to manipulate them in your scripts. These data type examples include strings, integers, dates, XML, and many more.

Chapter 3, Comparison Operators, evaluates multiple comparison operators and displays how to use each of these comparison operators. This chapter also displays how to leverage implied true and false comparison operators.

Chapter 4, Functions, Switches, and Loops Structures, displays the use of different data structures to perform repeatable actions. It provides examples on how to parse large arrays of data through looping structures and how to include overload parameters in these structures.

Chapter 5, Regular Expressions, explores PowerShell’s implementation of regular expressions. It evaluates the built-in comparison operators that provide expression validation and how to create complex expressions.

Chapter 6, Error and Exception Handling and Testing Code, shows you how to create code in a robust manner to avoid exceptions during execution. This chapter explains various built-in error and exception handling techniques, as well as support for legacy systems that don’t support PowerShell cmdlet triggers. It also explains the different items to be aware of during the testing cycle of your code.

Chapter 7, Session-based Remote Management, provides an insight into session-based management through PowerShell. It displays how to leverage the built-in WinRM to execute items on remote systems.

Chapter 8, Managing Files, Folders, and Registry Items, displays how to query, create, modify, and delete items in the filesystem and registry. This includes files, folders, registry keys, registry-named values, and properties.

Chapter 9, File, Folder, and Registry Attributes, ACLs, and Properties, dives deep into the interworking of files, folders, and registries. This chapter explains how to set file and folder standards and advanced attributes. It also displays how to manipulate ACLs to set permissions on files, folders, and registry items.

Chapter 10, Windows Management Instrumentation, explains how to use Windows Management Instrumentation (WMI) to query local and remote systems for advanced system information and the different cmdlets that provide access to a system’s WMI.

Chapter 11, XML Manipulation, explores eXtensible Markup Language (XML) and shows you how to interact with it using PowerShell. This chapter explains the different components that make up a proper XML document and how to interact with these individual components.

Chapter 12, Managing Microsoft Systems with Powershell, provides information on how to work with Windows users and groups, Windows services, Windows processes, and the manipulation of Windows features and roles.

Chapter 13, Automation of the Environment, explains how to invoke items for use with automation scripts. This chapter explains parent and child relationships because they pertain to linking scripts together. It also explores Desired Configuration Management (DCM) and configuration baselines.

Chapter 14, Script Creation Best Practices and Conclusion, provides best practice recommendations for utilizing PowerShell in your environment. This chapter concludes with some final thoughts from the author.

What you need for this book

To work through the examples provided in Mastering Windows PowerShell Scripting, you will need access to Windows 7 or a higher Windows operating system. You will also need Server 2008 R2 or a higher Windows Server operating system. The chapters in this book rely highly on Windows Management Framework 4.0 (PowerShell 4.0) and Remote Server Administration Tools. You will need to download and install both of these software packages on the systems you are running these examples on.

Who this book is for

Mastering Windows PowerShell Scripting has been designed for PowerShell scripters who can be both beginners and advanced-level coders. By reading this book, you will be able to gain in-depth knowledge of PowerShell and the best practices to develop scripts using this automation language. Previous scripting and coding experience will be helpful, though it is not required.

Conventions

In this book, you will find a number of styles of text 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, dummy URLs, user input, and Twitter handles are shown as follows: The get-service cmdlet is used to retrieve detailed information about Windows services.

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

# Retrieve the service sstatus and start the service if it is stopped. $status = (Get-service –DisplayName Windows Audio ).Status If ($status –like Stopped )

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: To add a firewall rule on a system using the netsh command, you need to open PowerShell with the Run as Administrator option

Note

Warnings or important notes appear in a box like this.

Tip

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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via 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

Оцените статью