Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Mastering PowerCLI
Mastering PowerCLI
Mastering PowerCLI
Ebook705 pages7 hours

Mastering PowerCLI

Rating: 0 out of 5 stars

()

Read preview

About this ebook

If you are a system administrator with a working knowledge of PowerShell and PowerCLI who wants to perform quick and easy scripting, but at the same time achieve complex results and write production-grade scripts, then this book is for you.
LanguageEnglish
Release dateOct 16, 2015
ISBN9781785287084
Mastering PowerCLI

Related to Mastering PowerCLI

Related ebooks

System Administration For You

View More

Related articles

Reviews for Mastering PowerCLI

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Mastering PowerCLI - Debnath Sajal

    Table of Contents

    Mastering PowerCLI

    Credits

    Foreword

    About the Author

    Acknowledgment

    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. PowerShell and PowerCLI Refresher

    The essence of PowerShell and PowerCLI

    The history of scripting

    PowerShell

    PowerCLI

    The vSphere PowerCLI package

    The vCloud PowerCLI package

    Implementing programming constructs in PowerShell

    Conditional logic

    Conditional logic using loops

    The difference between Foreach and Foreach-object

    Automation through PowerShell scripts

    Running and scheduling scripts

    Using version control with GitHub

    The fork & pull model

    The shared repository model

    Branch

    Testing your scripts using Pester

    Connecting to a vCenter and other VMware environments using PowerCLI cmdlets

    Summary

    2. Reusable Advanced Functions and Scripts

    Specifying function attributes

    Specifying parameter attributes

    Using parameter validation attributes

    Dynamic parameters

    Switch parameters

    PowerShell help files

    Creating comment-based help

    Error handling in PowerShell

    Summary

    3. Deploying vSphere Hosts

    Image Builder with PowerCLI

    Using host profiles

    Configuring Auto Deploy for ESXi hosts

    Adding hosts to a vCenter server

    Summary

    4. Managing Networks

    Managing vSphere standard switches

    Managing networking for ESXi

    Managing vSphere distributed switches

    Managing port groups

    Creating private VLANs

    Configuring vSphere network I/O control

    Configuring Netflow

    Working with ports

    Configuring traffic shaping

    Configuring port blocking

    Configuring the security policy

    Configuring the teaming policy

    Summary

    5. Managing Storage

    Managing datastores

    Configuring Fibre Channel storage

    Configuring iSCSI storage

    Configuring NFS storage

    Configuring virtual SAN

    Using datastore clusters

    Using Raw Device Mapping

    Managing storage using storage policy-based management

    Cmdlets related to policy rules

    Cmdlets related to storage policy

    Cmdlets related to Spbm capabilities and compatible storage

    Cmdlets related to policy application

    Cmdlets related to policy backup and migration

    Applying VMFS resignaturing

    Configuring vFLASH using PowerCLI Extensions

    Summary

    6. Managing Clusters and Other Constructs

    Configuring vCenter logical constructs

    Folder

    Datacenter

    Cluster

    Configuring the Enhanced vMotion Compatibility mode

    Configuring High Availability

    Using Dynamic Resource Scheduling

    Using the DRS affinity and anti-affinity rules

    Managing resource pools

    Managing alarms

    Summary

    7. Managing Virtual Machines

    Creating virtual machines

    Modifying virtual machines

    Hard disks

    Network adapters and USB devices

    Passthrough devices

    Snapshots

    Resource configuration and policies

    Managing VMware tools in a VM

    Managing templates

    Managing OS customization specifications

    Managing the guest OS

    Managing vApps

    Summary

    8. Managing vSphere Security, SRM, vCloud Air, and vROps

    The vSphere Security Hardening Guide

    Managing vSphere Update Manager

    Configuring a firewall and services in an ESXi host

    Managing host profiles

    Managing vCenter Site Recovery Manager

    Managing vCloud Air

    Managing vRealize Operations Manager

    Summary

    9. Managing the vSphere API

    Using the Get-View cmdlet to return .NET View objects

    Using the ExtensionData property to return .NET View objects

    Using the vSphere API

    Creating a vSphere scheduled task

    Configuring Distributed Power Management

    Configuring Fault Tolerance

    Managing Content Libraries

    Managing SRM advanced configurations

    Generating PowerCLI code using Onyx

    PowerActions for vSphere Web Client

    Summary

    10. Using REST APIs

    Introducing REST APIs

    Introducing JSON

    Syntax rules

    Values

    The Invoke-RestMethod cmdlet

    vRealize Automation REST APIs

    Authenticating and getting a vRA token

    Managing tenants

    Creating a tenant

    Listing identity stores for a tenant

    Linking an identity store to a tenant

    Managing machines

    Listing shared and private catalog items

    Managing approvals

    Managing provisioned resources

    Managing network profiles

    Summary

    11. Creating Windows GUI

    Different ways to create a Windows GUI

    Building a GUI using Windows Forms

    Creating a button

    Creating a TextBox

    Creating ListBox

    Creating CheckBox

    Using SAPIEN PowerShell Studio

    Building GUI using WPF

    Summary

    12. Best Practices and Sample Scripts

    Best practices

    Security Hardening Script

    Capacity check report

    Parameter descriptions

    Using a proper editor

    Sublime Text

    ISESteroids

    Summary

    Index

    Mastering PowerCLI


    Mastering PowerCLI

    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: October 2015

    Production reference: 1131015

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78528-685-8

    www.packtpub.com

    Credits

    Author

    Sajal Debnath

    Reviewers

    Amit Agarwal

    Jason Gaudreau

    Kyle Ruddy

    Brian Wuchner

    Commissioning Editor

    Ashwin Nair

    Acquisition Editor

    Kevin Colaco

    Content Development Editor

    Arun Nadar

    Technical Editors

    Saurabh Malhotra

    Mitali Somaiya

    Copy Editors

    Roshni Banerjee

    Rashmi Sawant

    Project Coordinator

    Nikhil Nair

    Proofreader

    Safis Editing

    Indexer

    Priya Sane

    Production Coordinator

    Shantanu N. Zagade

    Cover Work

    Shantanu N. Zagade

    Foreword

    In the last nine years that I've been with VMware India, I have had the privilege of hearing from several CIOs and heads of infrastructure that VMware is an industry innovator and leader, creating amazing products that are disrupting and evolving businesses and the personal lives of many of us. I consider myself extremely lucky to be leading one of the best technical teams in the IT infrastructure space today.

    When one of these technical brains in my team, Sajal Debnath, who comes from a small village in West Bengal, told me that he is writing a book on Mastering PowerCLI, the first question I asked him was Why scripting?. I asked this question because scripting is a popular and great way to make up for a product's shortcomings or missing features, and it can be a real-time saver for administrators. But, to the best of my knowledge, every new release of VMware's products tends to have several features or enhancements that have been requested by our customers.

    Sajal told me that the reason he has been successful in meeting the demanding needs of his customers is his expertise in scripting. PowerCLI is a very powerful command-line tool that allows you to automate all aspects of vSphere management, including network, storage, VM, guest OS, and more. There are unimaginable things that you can do in a VMware environment, and it is impossible for any product to include all of these features. I've heard from some of my customers too that tasks, such as automatically controlling the growth of snapshots, reporting on thin provisioned disks and their over allocation, and so on, are areas where scripting comes to their rescue.

    The second question that I asked was, why the need to write a book on this topic when there was plenty of documentation available in VMware itself and the PowerCLI community? This is when I realized that most of the documentation available is predominantly written for software developers who are from a scripting background. Having known Sajal for the last four years, I know that he is very much customer-driven. Having interacted with several system administrators in his career, he wanted to write this book purely for VMware administrators who spend every single day managing a virtual environment.

    This book starts off with an introduction to PowerShell and PowerCLI. If you are new to it, then it walks you through the process of how to configure and manage hosts, VMs, and networks and storage in detail. But the chapters that I liked the most were Chapter 8, Managing vSphere Security, SRM, vCloud Air, and vROps and Chapter 10, Using REST APIs. Chapter 8, Managing vSphere Security, SRM, vCloud Air, and vROps, goes beyond normal vSphere management and deals with one of the most ignored aspects today, security. I have seen very few customers in India who give importance to security hardening of their VMware environments. With the increasing threat perception these days, it is absolutely imperative for you to pay attention to how you can keep environments secure. Chapter 10, Using REST APIs, discusses how you can use REST APIs to manage other VMware products beyond vSphere that may not have native PowerCLI cmdlets. Toward the end, it also gives you some sample scripts that you can use straightaway in your environments.

    I believe that VMware is a very exciting technology company that allows us to deeply influence and rapidly evolve technology and business for our customers, and I want to thank Sajal for writing this book.

    If this isn't enough to spark interest in reading further, I don't know what is! I highly recommend that you read this book.

    B. S. Nagarajan

    Senior Director, Systems Engineering, VMware India

    About the Author

    Sajal Debnath is a highly certified Cloud computing technocrat with more than 12 years of experience in virtualized data center design, Cloud computing, and BC/DR solutions. He is an EMCISA, VCAP-DCD/DCA, VCAP-CID/CIA, RHCE 4/5/6, RHCVA, Openstack, and ITIL certified person. He is presently associated with VMware Software India Pvt. Ltd. as a senior system engineer. Previously, he worked with France Telecom, Hewlett Packard, and many more in multiple roles. He is involved in prestigious Indian government projects, such as National Cloud, Digital Locker, and so on.

    Acknowledgment

    First and foremost, I would like to thank my wife, Ananya, for standing beside me throughout my career and writing this book. She has been my inspiration and motivation for continuing to improve my knowledge and move my career forward. During the writing of this book, I spent nearly every waking hour of my day either in the office or writing this book, including weekends. Whenever I felt low and lacked enthusiasm, she guided me through this phase; sometimes with me complaining and kicking. She had to bear with the grumpy me. She is my rock and I would like to dedicate this book to her.

    I would like to thank my parents for giving me the freedom to choose my career path and always believing in me, and my elder brother, Ujjwal, for being my best friend.

    Thank you Niladri Chakraborty for being there and supporting me. Without you, I wouldn't be where I am today.

    Thank you Kalyan Guin and Suprovat Sinha for supporting me through thick and thin.

    I must thank B S Nagarajan for supporting me throughout my career in VMware and helping whenever I required it. I hope that someday I can be more like you.

    I want to specially thank Naresh Purohit for always believing in me and being the guiding star for me both professionally and personally.

    Prashant Dwivedi, without you this book wouldn't have happened in the first place. Thank you for encouraging me so much.

    I want to thank Alan Renouf for taking time out of his busy schedule, supporting me, and providing me with access to the required materials and information.

    Thank you Brian Graf, Massimo Re Ferre, Dr. Tobias Weltner, and Jason Wasser for providing me with the material and support for this book.

    I would like to thank my reviewers, especially Kyle Ruddy, Jason Gaudreau, Amit Agarwal, and Brian Wuchner, for not only reviewing the book but also for giving me suggestions to improve it as well. I would also like to thank Arun Nadar for following up with me and arranging everything for me.

    Last but not least, thank you Packt Publishing for giving me the opportunity to write this book. I'd also like to thank every team member who contributed to this project, the external reviewers, and the other guys whom I didn't meet—your contributions were invaluable and this book wouldn't be what it is without you.

    About the Reviewers

    Amit Agarwal is a senior software engineer working with Great Software Laboratory (GS Lab), Pune, in its Cloud and infrastructure practice.

    He is a VMware Certified Professional 5 – Data Center Virtualization, VMware Certified Associate – Data Center Virtualization, and a VMware Certified Associate – Cloud. He is also a frequent contributor to the VMware Technology Network (VMTN).

    He has more than three years' experience working with PowerShell and VMware vSphere PowerCLI for building test automation frameworks and scripts, contributing to quality assurance for complex virtualization and network security products.

    GS Lab is a product development partner for software product companies with customers that include world-leading technology vendors, as well as start-ups. Our customer engagements span the entire product journey right from prototyping, to development, support, DevOps, and professional services.

    I would like to thank my colleagues from Calsoft—Amar, Archana, and Madhumita—for their help during my learning process. I also would like to thank my family and friends for their continuous support.

    Jason Gaudreau has over 24 years of industry experience. He is currently working as a senior product marketing engineer at VMware, a leading information technology provider of enterprise application solutions.

    He focuses on virtualization solutions and aligning infrastructure technologies to meet strategic business objectives. He has been concentrating on data center virtualization, desktop virtualization, and building internal private clouds in a variety of technical roles the past 10 years and more. He has been an active blogger on virtualization since 2012 at www.jasongaudreau.com and can be found on Twitter at @JAGaudreau. He is honored to have been designated as a vExpert by VMware in 2013-2015 and an EMC Elect in 2014.

    Before VMware, he was an IT architect for AdvizeX Technologies and in IT leadership at Unum Group, where he helped to develop the organization's IT strategy.

    When not talking shop, he enjoys spending time with his wife, Christine, and his two kids, Dylan and Tyler.

    Kyle Ruddy is a senior technical consultant. He has over 10 years of experience in the IT field. He has obtained multiple certifications, including VCAP-DCD and DCA, held the VCP since Version 3, GCWN (GIAC Certified Windows Security Administrator), and MCITP: SA, MCSE, among others. He has also been a VMware vExpert since 2012, a Cisco Champion since 2014, and a leader for the Indy VMUG since 2011.

    You can contact him on LinkedIn at www.linkedin.com/in/kmruddy, Twitter at @kmruddy, or through his blog at www.thatcouldbeaproblem.com.

    Brian Wuchner is a deputy IT director of a government agency. He has over 15 years of industry experience in infrastructure automation, directory services, server hosting, storage, and data center virtualization. He holds the EMC proven professional cloud architect and VMware VCP5-DCV certifications. He was awarded the VMware vExpert title from VMware in 2011-2015. He can be contacted on LinkedIn at http://www.linkedin.com/in/bwuch, Twitter at @bwuch, or through his blog at http://enterpriseadmins.org.

    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

    If you are a system administrator who manages a considerable-sized environment, then I do not need to elaborate on the importance of scripting to you. Scripting was and always will be one of the most important arsenals in a system administrator's weaponry. With the term scripting, till very recently typically bash or other such shell scripts used to come to mind and more advanced ones, such as Perl, PHP, or Ruby. I love this scripting language for the sheer beauty and power that it presents. If you are coming from a *NIX environment, PowerShell will completely change your perception about scripting. If you are managing a vSphere environment, then besides vRealize Orchestrator, PowerCLI is the most powerful tool available to help you automate the different aspects of a vSphere environment. Probably, if I need to get something done really quickly, I will still rely on PowerCLI scripting.

    In all my years of experience as a working professional and before that as a student and teacher, I have seen primarily two methods of explanation: the first approach, and the most widely used one, is to take an example problem and solve it while explaining the solution to the student. This way, the student learns how to solve a particular type of problem. The second approach is the one in which a teacher explains the basic logic and principles of a solution behind the problem, and then asks the students to solve the problem all by themselves. As a student, I always found myself struggling with the first approach. Though the first approach was easier to understand, it tends to limit my knowledge to solving only similar problems. Because of the lack of the understanding of the underlying logic, faced with a new problem, I could not solve it most of the time. This happened especially in mathematical problems. It was like showing me a program written in C to implement Dijkstra's algorithm and explaining how this program was written. Knowing this, will I be able to implement any other algorithm in C or utilize Dijkstra's algorithm for my advantage? Probably not. Instead, if someone teaches me the different aspects of C language and how to write programs using C, then I can utilize this knowledge to write any programs.

    You may disagree or agree with me, but I always preferred the second approach as it worked for me and gave me a better understanding and hold on the topic.

    So, throughout this book, I tried to explain all the building blocks of advanced PowerShell and PowerCLI scripting and then provided examples to showcase what I am trying to say. I tried this approach with the hope that it will give you a better understanding and clarity of the underlying constructs so that you can build on top of this.

    What this book covers

    Chapter 1, PowerShell and PowerCLI Refresher, refreshes the basics of PowerShell and introduces you to concepts that are necessary to develop, run, and test PowerShell scripts using PowerCLI cmdlets.

    Chapter 2, Reusable Advanced Functions and Scripts, covers how to create reusable advanced functions and scripts. Advanced functions can be used like cmdlets in PowerShell and give much more power over normal functions.

    Chapter 3, Deploying vSphere Hosts, covers how to automatically deploy and configure ESXi hosts using different tools, such as Image Builder, Auto Deploy, and Host Profiles.

    Chapter 4, Managing Networks, discusses how to configure and manage vSphere networking through standard and distributed switches using PowerCLI.

    Chapter 5, Managing Storage, discusses how to create and manage storage in a vSphere environment, including SAN, NAS, iSCSI, and VSAN.

    Chapter 6, Managing Clusters and Other Constructs, covers how to manage logical constructs in a vCenter environment, including but not limited to HA and DRS clusters.

    Chapter 7, Managing Virtual Machines, covers how to configure the different aspects of virtual machines and guest operating systems using PowerCLI.

    Chapter 8, Managing vSphere Security, SRM, vCloud Air, and vROps, covers security hardening and patching vSphere environments along with other VMware solutions, such as SRM, vCloud Air, and vRealize Operations Manager.

    Chapter 9, Managing the vSphere API, discusses how to use the vSphere API in PowerCLI and how we can manage advanced aspects of a vSphere environment using APIs.

    Chapter 10, Using REST APIs, discusses Representational state transfer (REST) APIs and how PowerCLI can be used to manage the VMware vRealize Automation environment using REST APIs.

    Chapter 11, Creating Windows GUI, discusses how to create a Windows graphical user interface (GUI) using PowerShell and other tools.

    Chapter 12, Best Practices and Sample Scripts, describes PowerShell scripting best practices. This chapter also covers two sample scripts, one to get a security report and another to find the capacity of a vSphere environment.

    What you need for this book

    To test the examples provided in Chapters 1 to 7 and to practice further, you need to have access to a vSphere environment with vCenter and ESXi servers. For Chapter 8, Managing vSphere Security, SRM, vCloud Air, and vROps, you need to have access to the vCloud Air and vRealize Operations Manager environment. For Chapter 10, Using REST APIs, you need to have access to the vRealize Automation environment. I have used the following versions of different software to write this book:

    PowerShell Version 5.0.10532.0

    For most part PowerCLI 6.0 R1, and for Chapter 8, Managing vSphere Security, SRM, vCloud Air, and vROps PowerCLI 6.0 R2

    ESXi 6.0

    vCenter 6.0

    vRealize Automation 6.2

    vRealize Operations 6.2

    If you do not have access to physical server-grade systems, you can build your test setup in a lab environment as well. For most of the book, I used a Whitebox desktop with 32 GB RAM in it. To build a vSphere environment, I have used VMware Workstation Version 12 and nested VMs for ESXi hosts. For vRealize Operations Manager, SRM, and vCloud Air, I had to rely on traditional resources.

    So, before you start reading the chapters, I suggest that you get ready to build a vSphere lab. Also, as the chapters progress, we will build the lab step by step because different chapters cover different areas of a vSphere environment, starting from the ground up.

    Who this book is for

    This book is aimed at anyone who has a working knowledge of PowerShell and PowerCLI and who wants to script a vSphere environment like a pro with PowerCLI and PowerShell. This book is written from a system admin's perspective, so you do not need to be a development wizard. You just need to know the basics of programming and programming logic so that you can utilize the knowledge gained in this book to your advantage.

    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: I strongly suggest that you type Get-Help in PowerShell and read the output.

    A block of code is set as follows:

    Switch (value) {

    Pattern 1 {Script Block}

    Pattern 2 {Script Block}

    Pattern n {Script Block}

    Default  {Script Block}

    }

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

    {

      firstName: Sajal,

      lastName: Debnath,

     

      isWorking: true,

      age: 35,

      address: {

        streetAddress: 2435 A.B.C Road,

        city: New Delhi,

        state: Karnataka,

     

        postalCode: 123456

      },

      contactNumbers: [

        {

          type: home,

          number: 1234567897

        },

        {

          type: office,

          number: 123456789876

        }

      ],

      children: [],

      spouse: null

    }

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

    PS C:\> Connect-CIServer -Server -User -Password

    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 unblock it, right-click on the file, and select Properties. From the Properties menu, select unblock.

    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 <[email protected]>, 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 on www.packtpub.com/authors.

    Customer

    Enjoying the preview?
    Page 1 of 1