39,59 €
VMware vSphere PowerCLI, a free extension to Microsoft Windows PowerShell, enables you to automate the management of a VMware vSphere or vCloud environment.
This book will show you how to automate your tasks and make your job easier. Starting with an introduction to the basics of PowerCLI, the book will teach you how to manage your vSphere and vCloud infrastructure from the command line. To help you manage a vSphere host overall, you will learn how to manage vSphere ESXi hosts, host profiles, host services, host firewall, and deploy and upgrade ESXi hosts using Image Builder and Auto Deploy. The next chapter will not only teach you how to create datastore and datastore clusters, but you’ll also work with profile-driven and policy-based storage to manage your storage. To create a disaster recovery solution and retrieve information from vRealize Operations, you will learn how to use Site Recovery Manager and vRealize Operations respectively. Towards the end, you’ll see how to use the REST APIs from PowerShell to manage NSX and vRealize Automation and create patch baselines, scan hosts against the baselines for missing patches, and re-mediate hosts.
By the end of the book, you will be capable of using the best tool to automate the management and configuration of VMware vSphere.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 550
Veröffentlichungsjahr: 2017
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: February 2014
Second edition: February 2017
Production reference: 1200217
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-801-7
www.packtpub.com
Author
Robert van den Nieuwendijk
Copy Editors
Safis Editing
Dipti Mankame
Reviewer
Kim Bottu
Project Coordinator
Shweta H. Birwatkar
Commissioning Editor
Vijin Boricha
Proofreader
Safis Editing
Acquisition Editor
Prachi Bisht
Indexer
Pratik Shirodkar
Content Development Editor
Abhishek Jadhav
Graphics
Kirk D'Penha
Technical Editor
Gaurav Suri
Production Coordinator
Shantanu N. Zagade
Robert van den Nieuwendijk is an IT veteran from the Netherlands with over thirty years of experience in Information Technology. He holds a bachelor degree in software engineering. After working a few years as a programmer of air traffic control and vessel traffic management systems, he started his own company Van den Nieuwendijk Informatica in 1988. Since then he has worked as a freelance systems administrator of OpenVMS, Windows Server, Linux, and VMware vSphere systems, for Dutch governmental organizations and cloud providers. During winter he is also a ski and snowboard instructor at an indoor ski school.
With his background as a programmer, he always tries to make his job easier by writing programs or scripts to perform repeating tasks. In the past, he used the C programming language, OpenVMS DCL, Visual Basic Script and KiXtart to do this. Now, he uses Microsoft PowerShell and VMware PowerCLI for all of his scripting work.
Robert is a frequent contributor and moderator at the VMware VMTN Communities. Since 2012 VMware awarded him the vExpert title for his significant contributions to the community and a willingness to share his expertise with others.
He has a blog at http://rvdnieuwendijk.com where he writes mainly about VMware PowerCLI, Microsoft PowerShell, and VMware vSphere.
If you want to get in touch with Robert, then you can find him on Twitter. His username is @rvdnieuwendijk.
Robert is also the author of Learning PowerCLI, Packt Publishing.
I would like to thank my wife Ali for supporting me writing this second book.
I also want to thank the people at Packt Publishing for giving me the opportunity to update the Learning PowerCLI book and write this second edition.
Kim Bottu is the virtualization engineer in the EMEA region for an international Biglaw firm, where he focuses on virtual datacenter operations, optimization, and design.
In his current role, he takes care of the consolidated virtual datacenters in Asia and Europe, and he is the SME for the EMEA Litigation virtual datacenters.
He holds the following certifications and honors: VCA-NV, VCP5-DCV, VCP6-DCV, VCAP5-DCD, VCAP6-DCV Design, and TOGAF 9 certified. He has also been named vExpert 2016 and vExpert 2017.
Kim currently lives in Belgium and is a proud dad of a daughter named Zoey. In his spare time you might find him playing with his daughter, reading books, or riding his mountain bike.
Kim can be reached at www.vMusketeers.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.com and 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.
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 on this book's Amazon page at https://www.amazon.com/dp/1786468018.
If you'd like to join our team of regular reviewers, you can e-mail 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!
VMware PowerCLI is a command-line automation and scripting tool that provides a Microsoft PowerShell interface to the VMware vSphere and vCloud products. Learning PowerCLI shows you how to install and use PowerCLI to automate the management of your VMware vSphere environment. With lots of examples, this book will teach you how to manage vSphere from the command line and how to create advanced PowerCLI scripts.
Chapter 1 , Introduction to PowerCLI, gets you started using PowerCLI. First, you will see how to download and install PowerCLI. Then, you will learn to connect to and disconnect from the vCenter and ESXi servers and retrieve a list of all of your hosts and virtual machines.
Chapter 2 , Learning Basic PowerCLI Concepts, introduces the Get-Help, Get-Command, and Get-Member cmdlets. It explains the difference between PowerShell Providers and PSdrives. You will see how you can use the raw vSphere API objects from PowerCLI and how to use the New-VIProperty cmdlet to extend a PowerCLI object.
Chapter 3 , Working with Objects in PowerShell, concentrates on objects, properties, and methods. This chapter shows how you can use the pipeline to use the output of one command as the input of another command. You will learn how to use the PowerShell object cmdlets and how to create PowerShell objects.
Chapter 4 , Managing vSphere Hosts with PowerCLI, covers the management of the vSphere ESXi servers. You will see how to add hosts to the vCenter server and how to remove them. You will work with host profiles, host services, Image Builder, and Auto Deploy, as well as with the esxcli command and the vSphere CLI commands from PowerCLI.
Chapter 5 , Managing Virtual Machines with PowerCLI, examines the lifecycle of virtual machines-from creating to removing them. Creating templates, updating VMware Tools and upgrading virtual hardware, running commands in the guest OS, and configuring fault tolerance are some of the topics discussed in this chapter.
Chapter 6 , Managing Virtual Networks with PowerCLI, walks you through vSphere Standard Switches and vSphere Distributed Switches, port groups, and network adapters. It shows you how to configure host networking and how to configure the network of a virtual machine.
Chapter 7 , Managing Storage, explores creating and removing datastores and datastore clusters, working with Raw Device Mapping, configuring software iSCSI initiators, Storage I/O Control, and Storage DRS.
Chapter 8 , Managing High Availability and Clustering, covers HA and DRS clusters, DRS rules and DRS groups, resource pools, and Distributed Power Management.
Chapter 9 , Managing vCenter Server, shows you how to work with privileges, work with roles and permissions, manage licenses, configure alarm definitions, alarm action triggers, and retrieve events.
Chapter 10 , Patching ESXi Hosts and Upgrading Virtual Machines, focusses on using VMware vSphere Update Manager to download patches, creating baselines and baseline groups, testing virtual machines and hosts for compliance, staging patches, and remediating inventory objects.
Chapter 11 , Managing VMware vCloud Director and vCloud Air, covers connecting to vCloud servers, retrieving organizations, virtual datacenters, organization networks, and users, using vCloud virtual machines and appliances, and using snapshots.
Chapter 12 , Using Site Recovery Manager, explores the Meadowcroft.SRM module to manage SRM protection groups, protecting virtual machines and running recovery plans to migrate or fail-over virtual machines from the protected site to the recovery site.
Chapter 13 , Using vRealize Operations Manager, shows you to use alerts, retrieve recommendations, statistical data, solutions, and traversalSpecs, manage local user accounts and user roles and create and retrieve reports.
Chapter 14 , Using REST API to Manage NSX and vRealize Automation, walks you through REST APIs with examples from VMware NSX and vRealize Automation using basic authentication and bearer tokens, XML, and JSON.
Chapter 15 , Reporting with PowerCLI, concentrates on retrieving log files and log bundles, performance reporting, exporting reports to CSV files, generating HTML reports, sending reports by e-mail, and reporting the health of your vSphere environment with the vCheck script.
To run the example PowerCLI scripts given in this book, you need the following software:
If you don't have specific software installed, you can use the VMware Hands-on Labs at https://labs.hol.vmware.com/ to test the scripts.
The scripts in this book are tested using VMware PowerCLI 6.5 Release 1, VMware vCenter Server 6.5, and VMware ESXi 6.5. Microsoft PowerShell and VMware PowerCLI are free. You can download a free 60-day evaluation of VMware vCenter Server and VMware ESXi from the VMware website. It is not possible to modify the settings on the free VMware vSphere Hypervisor using PowerCLI.
This book is written for VMware vSphere administrators who want to automate their vSphere environment using PowerCLI. It is assumed that you have at least a basic knowledge of VMware vSphere. If you are not a vSphere administrator, but you are interested in learning more about PowerCLI, then this book will also give you some basic knowledge of vSphere.
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 to us as it helps us develop titles that you will 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 .
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.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-PowerCLI-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-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 will be accepted, and the errata will be 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 will appear under the Errata section.
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.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Have you ever had to create 200 virtual machines in a short period of time, change a setting on all of your hosts, or make an advanced report for your boss to show how full the hard disks of your virtual machines are? If you have, you know that performing these tasks using the vSphere web client will take a lot of time. This is where automation can make your job easier. VMware PowerCLI is a powerful tool that can perform these tasks and much more. And the best thing is that it is free!
VMware PowerCLI is a command-line interface (CLI) distributed as a collection of Microsoft PowerShell modules and snap-ins. Microsoft PowerShell is Microsoft's command shell and scripting language, designed with the systems administrator in mind. Microsoft PowerShell is available on every Microsoft Windows server or workstation since Windows Server 2008 R2 and Windows 7. VMware PowerCLI is an extension to Microsoft PowerShell. This means that all of the features of PowerShell can be used in PowerCLI. You can use PowerCLI to automate your vSphere hosts, virtual machines, virtual networks, storage, clusters, vCenter Servers, and more.
In this chapter, you will learn:
In this section, you will learn how to download and install PowerCLI 6.5 Release 1. First, we will list the requirements for PowerCLI 6.5 Release 1. After downloading PowerCLI from the VMware website, we will install PowerCLI on your system.
You can install VMware PowerCLI 6.5 Release 1, the version used for writing this book, on the following 64-bit operating systems:
VMware PowerCLI 6.5 Release 1 is compatible with the following PowerShell versions:
If you want to work with VMware PowerCLI 6.5 Release 1, make sure that the following software is present on your system:
Before you can install PowerCLI, you have to download the PowerCLI installer from the VMware website. You will need a My VMware account to do this.
Perform the following steps to download PowerCLI:
Perform the following steps to install PowerCLI:
After installing PowerCLI, you will have a VMware PowerCLI icon on your desktop. If you installed PowerCLI on a 64-bit computer, you will also have a VMware PowerCLI (32-Bit) icon. Some PowerCLI commands only work in the 32-bit version of PowerCLI. So keep both versions.
When you start PowerCLI for the first time, you will get the following screen:
You are asked to participate in the VMware Customer Improvement Program (CEIP). Type J to participate in the CEIP or type L to leave.
If you didn't get the text from the preceding screenshot, you may get the following error message:
. : File C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
Then, read the following section, Modifying the PowerShell execution policy, to solve this problem.
If this is the first time that you are using Microsoft PowerShell on the computer on which you installed PowerCLI, you have to change the execution policy to be able to start PowerCLI.
The Microsoft PowerShell execution policies define when you can run scripts or load configuration files. The possible values for the execution policy are Restricted, AllSigned, RemoteSigned, Unrestricted, Bypass, and Undefined.
Policy
Description
Restricted
This is the default execution policy. It allows you to run commands at the Command Prompt, but disables the execution of scripts. It will also disable the start of PowerCLI.
AllSigned
With the AllSigned execution policy, scripts can run, but they must be signed by a trusted publisher. If you run a script by a publisher that is not trusted yet, you will see a prompt asking whether you trust the publisher of the script.
RemoteSigned
The RemoteSigned execution policy allows you to run scripts that you have written on the local computer. Any script downloaded from the Internet must be signed by a trusted publisher or must be unblocked.
Unrestricted
When the execution policy is set to Unrestricted, unsigned scripts can run. If you run a script that has been downloaded from the Internet, you will get a security warning saying that this script can potentially harm your computer and asking whether you want to run this script.
Bypass
The Bypass execution policy blocks nothing and displays no warnings or prompts. This execution policy is designed for configurations in which a Microsoft PowerShell script is built into a larger application that has its own security model.
Undefined
The Undefined execution policy removes the execution policy from the current scope. If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy. The Undefined execution policy will not remove an execution policy that is set in a Group Policy scope.
You can check the current execution policy setting with the following command:
PowerCLI C:\> Get-ExecutionPolicyGet-ExecutionPolicy is a Microsoft PowerShell commandlet (cmdlet). Cmdlets are commands built into PowerShell or PowerCLI. They follow a verb-noun naming convention. The get cmdlets retrieve information about the item that is specified as the noun part of the cmdlet.
Set the execution policy to RemoteSigned to be able to start PowerCLI and run scripts written on the local computer with the Set-ExecutionPolicy -ExecutionPolicy RemoteSigned command.
You have to run the Set-ExecutionPolicy -ExecutionPolicy RemoteSigned command from a PowerShell or PowerCLI session that you started using the Run as Administrator option, or you will get the following error message:
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
If you are using both the 32-bit and the 64-bit versions of PowerCLI, you have to run this command in both versions.
In the following screenshot of the PowerCLI console, you will see the output of the Set-ExecutionPolicy -ExecutionPolicy RemoteSigned command if you run this command in a PowerCLI session started with Run as Administrator.
You can get more information about execution policies by typing the following command:
PowerCLI C:\> Get-Help about_Execution_PoliciesTo get more information about signing your scripts, type the following command:
PowerCLI C:\> Get-Help about_signingIf you get an error message saying Get-Help could not find about_Execution_Policies in a help file, you have to run the Update-Help cmdlet in a PowerShell, or PowerCLI session started with Run as Administrator first. The Update-Help cmdlet downloads the newest help files for Microsoft PowerShell modules and installs them on your computer. Because Microsoft updates the Microsoft PowerShell help files on a regular basis, it is recommended to run the Update-Help cmdlet on a regular basis also.
If you want certain PowerCLI commands to be executed every time you start a PowerCLI session, you can put these commands in a PowerShell profile. The commands in a PowerShell profile will be executed every time you start a new PowerCLI session. There are six PowerShell profiles, two specific for the PowerShell console, two specific for the PowerShell Integrated Scripting Environment (ISE), and two used by both the PowerShell console and the PowerShell ISE. The PowerShell console and the PowerShell ISE have their own profiles for:
The two profiles used by both the PowerShell console and the PowerShell ISE are:
You can retrieve the locations for the different profiles of the PowerShell console by executing the following command in the PowerShell console. In this command, the $PROFILE variable is a standard PowerShell variable that returns an object containing the locations of the PowerShell profiles. This object is piped to the Format-List -Force command to display all of the properties of the $PROFILE object in a list:
PowerCLI C:\> $PROFILE | Format-List -Force AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\p rofile.ps1AllUsersCurrentHost : C:\Windows\System32\WindowsPowerShell\v1.0\M icrosoft.PowerShell_profile.ps1CurrentUserAllHosts : C:\Users\robert\Documents\WindowsPowerShell\ profile.ps1CurrentUserCurrentHost : C:\Users\robert\Documents\WindowsPowerShell\ Microsoft.PowerShell_profile.ps1Length : 76Downloading the example code
Detailed steps to download the code bundle are mentioned in the Preface of this book. Please have a look.
The code bundle for the book is also hosted on GitHub at: https://github.com/rosbook/effective_robotics_programming_with_ros . We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/ . Check them out!
As you can see in the output of the preceding command, the $PROFILE object has four properties AllUsersAllHosts, AllUsersCurrentHost, CurrentUserAllHosts, and CurrentUserCurrentHost that contain the locations of the different profiles.
To list the locations of the PowerShell profiles of the PowerShell ISE, you have to execute the preceding command in the PowerShell ISE. This gives the following output:
PS C:\> $PROFILE | Format-List -Force AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\p rofile.ps1AllUsersCurrentHost : C:\Windows\System32\WindowsPowerShell\v1.0\M icrosoft.PowerShellISE_profile.ps1CurrentUserAllHosts : C:\Users\robert\Documents\WindowsPowerShell\ profile.ps1CurrentUserCurrentHost : C:\Users\robert\Documents\WindowsPowerShell\ Microsoft.PowerShellISE_profile.ps1Length : 79You can start the PowerShell ISE from a Command Prompt by running powershell_ise.exe. You can start the PowerShell ISE from within a PowerShell console with the alias ise.
The default value for the $PROFILE variable is the value of the $PROFILE.CurrentUserCurrentHost property. So you can use $PROFILE instead of $PROFILE.CurrentUserCurrentHost.
You can determine if a specific profile exists by using the Test-Path cmdlet. The following command will test if the profile specified by $PROFILE exists:
PowerCLI C:\> Test-Path -Path $PROFILEFalseIf a profile does not exist, as in the preceding example, you can create the profile using the New-Item cmdlet. If the directories in the path do not exist, by using the -Force parameter the New-Item cmdlet will create the directories. The following command will create the current user/current host profile and will also create the missing directories in the path:
PowerCLI C:\> New-Item -Path $PROFILE -ItemType file -Force Directory: C:\Users\robert\Documents\WindowsPowerShell Mode LastWriteTime Length Name---- ------------------ ------ -----a-- 1/7/2017 2:01 PM 0 Microsoft.PowerShell_pro file.ps1After creating the PowerShell profile, you can edit the profile using the PowerShell ISE with the following command:
PowerCLI C:\> ise $PROFILEIf you put the commands from the preceding section, Modifying the PowerShell execution policy, the new colors of the messages will be used in all of your PowerCLI sessions.
If you are logged in to your computer with a domain account, you can use your Windows session credentials to connect to a vCenter or ESXi server. If you are not logged in to your computer with a domain account or your domain account has no rights in vSphere, you have to supply account information every time you connect to a vCenter or ESXi server.
To prevent yourself from having to do this, you can store credentials in the credential store. These stored credentials will be used as default if you connect to a server that is stored in the credential store. You can use the -SaveCredentials parameter of the Connect-VIServer cmdlet to indicate that you want to save the specified credentials in the local credential store, as follows:
PowerCLI C:\> Connect-VIServer -Server 192.168.0.132 -User admin -Password pass -SaveCredentialsYou can also create a new entry in the credential store with the New-VICredentialStoreItem cmdlet:
PowerCLI C:\> New-VICredentialStoreItem -Host 192.168.0.132 -User Admin -Password passYou can not only store credentials for vCenter Servers but also for ESXi servers, using the following command:
PowerCLI C:\> New-VICredentialStoreItem -Host ESX1 -User root -Password VMware1!To get a listing of all of your stored credentials, type the following command:
PowerCLI C:\> Get-VICredentialStoreItemAnd to remove a stored credential you can use the following command:
PowerCLI C:\> Remove-VICredentialStoreItem -Host ESX1 -User rootThe stored credentials are stored in a file on your computer. The default credential store file location is: %APPDATA%\VMware\credstore\vicredentials.xml. But it is also possible to create other credential store files. You can see the contents of the default credential store file with the following command:
PowerCLI C:\> Get-Content -Path $env:APPDATA\VMware\credstore \vicredentials.xmlThe passwords stored in a credential store file are encrypted. But you can easily retrieve the stored passwords with the following command:
PowerCLI C:\> Get-VICredentialStoreItem |>> Select-Object -Property Host,User,PasswordThe passwords in the stored credentials are encrypted. Only the user who created the item can decrypt the password.
Now that we know how to connect to a server, let's do something useful with PowerCLI. Most of the people who begin using PowerCLI create reports, so create a list of all of your virtual machines as your first report. You have to use the Get-VM cmdlet to retrieve a list of your virtual machines. The syntax of the Get-VM cmdlet is as follows. The first parameter set is the default:
Get-VM [[-Name] <String[]>] [-Server <VIServer[]>] [-Datastore <StorageResource[]>] [-Location <VIContainer[]>] [-Tag <Tag[]>] [-NoRecursion] [<CommonParameters>]The second parameter set is for retrieving virtual machines connected to specific virtual switches:
Get-VM [[-Name] <String[]>] [-Server <VIServer[]>] [-VirtualSwitch <VirtualSwitchBase[]>] [-Tag <Tag[]>] [<CommonParameters>]The third parameter set is for retrieving virtual machines by ID:
Get-VM [-Server <VIServer[]>] -Id <String[]> [<CommonParameters>]The -Id parameter is required. The fourth parameter set is for retrieving virtual machines by related object:
Get-VM -RelatedObject <VmRelatedObjectBase[]> [<CommonParameters>]The -RelatedObject parameter is required. You can use these four parameter sets to filter the virtual machines based on name, server, datastore, location, distributed switch, ID, or related object.
Create your first report with the following command:
PowerCLI C:\> Get-VMThis will create a list of all of your virtual machines. You will see the name, power state, the number of CPU's, and the amount of memory in GB for each virtual machine, as shown in the following command-line output:
Name PowerState NumCPUs MemoryGB---- ---------- -------- --------Dc1 PoweredOn 2 4.000VM1 PoweredOn 1 0.250DNS1 PoweredOn 2 8.000The Name, PowerState, NumCPU, and MemoryGB properties are the properties that you will see by default if you use the Get-VM cmdlet. However, the virtual machine object in PowerCLI has a lot of other properties that are not shown by default. You can see them all by piping the output of the Get-VM cmdlet to the Format-List cmdlet using the pipe character |. The Format-List cmdlet displays object properties and their values in a list format, as shown in the following command-line output:
PowerCLI C:\> Get-VM -Name DC1 | Format-List -Property * Name : DC1PowerState : PoweredOffNotes :Guest : DC1:NumCPU : 1CoresPerSocket : 1MemoryMB : 4096MemoryGB : 4VMHostId : HostSystem-host-10VMHost : 192.168.0.133VApp :FolderId : Folder-group-v9Folder : Discovered virtual machineResourcePoolId : ResourcePool-resgroup-8ResourcePool : ResourcesHARestartPriority : ClusterRestartPriorityHAIsolationResponse : AsSpecifiedByClusterDrsAutomationLevel : AsSpecifiedByClusterVMSwapfilePolicy : InheritVMResourceConfiguration : CpuShares:Normal/1000 MemShares:Normal/40960Version : v13PersistentId : 50399fa1-6d65-a26f-1fd2-b635d0e8610fGuestId : windows9Server64GuestUsedSpaceGB : 30.000001807697117328643798828ProvisionedSpaceGB : 34.175447797402739524841308594DatastoreIdList : {Datastore-datastore-11}ExtensionData : VMware.Vim.VirtualMachineCustomFields : {}Id : VirtualMachine-vm-46Uid : /VIServer=vsphere.local\administrator@192. 168.0.132:443/VirtualMachine=VirtualMachin e-vm-46/Client : VMware.VimAutomation.ViCore.Impl.V1.VimCli EntYou can select specific properties with the Select-Object cmdlet. Say you want to make a report that shows the Name, Notes, VMHost, and Guest properties for all your virtual machines. You can do that with the following command:
PowerCLI C:\> Get-VM | Select-Object -Property Name,Notes,VMHost,GuestThe output of the preceding command is as follows:
Name Notes VMHost Guest---- ----- ------ -----DC1 192.168.0.133 DC1:VM1 192.168.0.134 VM1:DNS1 DNS Server 192.168.0.134 DNS1:In PowerShell, parameters can be positional. This means that you can omit the parameter name if you put the parameter values in the right order. In the preceding example, the -Property parameter of the Select-Object cmdlet can be omitted. So the preceding command can also be written as:
PowerCLI C:\> Get-VM | Select-Object Name,Notes,VMHost,GuestIn the examples in this book, I will always use the parameter names.
You will probably have also seen the following warning messages:
WARNING: The 'Description' property of VirtualMachine type is deprecated. Use the 'Notes' property instead.WARNING: The 'HardDisks' property of VirtualMachine type is deprecated. Use 'Get-HardDisk' cmdlet instead.WARNING: The 'NetworkAdapters' property of VirtualMachine type is deprecated. Use 'Get-NetworkAdapter' cmdlet instead.WARNING: The 'UsbDevices' property of VirtualMachine type is deprecated. Use 'Get-UsbDevice' cmdlet instead.WARNING: The 'CDDrives' property of VirtualMachine type is deprecated. Use 'Get-CDDrive' cmdlet instead.WARNING: The 'FloppyDrives' property of VirtualMachine type is deprecated. Use 'Get-FloppyDrive' cmdlet instead.WARNING: The 'Host' property of VirtualMachine type is deprecated. Use the 'VMHost' property instead.WARNING: The 'HostId' property of VirtualMachine type is deprecated. Use the 'VMHostId' property instead.WARNING: PowerCLI scripts should not use the 'Client' property. The property will be removed in a future release.These warning messages show the properties that should not be used in your scripts because they are deprecated and might be removed in a future PowerCLI release. Personally, I like these warnings because they remind me of the properties that I should not use anymore. But if you don't like these warnings, you can stop them from appearing with the following command:
PowerCLI C:\> Set-PowerCLIConfiguration -DisplayDeprecationWarnings $false -Scope UserYou can also use wildcard characters to select specific virtual machines. To display only the virtual machines that have names that start with an A or a, type the following command:
PowerCLI C:\> Get-VM -Name A*Parameter values are not case sensitive. The asterisk (*) is a wildcard character that matches zero or more characters, starting at the specified position. Another wildcard character is the question mark (?), which matches any character at the specified position. To get all virtual machines with a three-letter name that ends with e, use the following command:
PowerCLI C:\> Get-VM -Name ??eYou can also specify some specific characters, as shown in the following command:
PowerCLI C:\> Get-VM -Name [bc]*The preceding command displays all of the virtual machines that have names starting with b or c. You can also specify a range of characters, as shown in the following command:
PowerCLI C:\> Get-VM -Name *[0-4]The preceding command lists all of the virtual machines that have names ending with 0, 1, 2, 3, or 4.
If you want to filter properties that don't have their own Get-VM parameter, you can pipe the output of the Get-VM cmdlet to the Where-Object cmdlet. Using the Where-Object cmdlet, you can set the filter on any property. Let's display a list of all of your virtual machines that have more than one virtual CPU using the following command:
PowerCLI C:\> Get-VM | Where-Object {$_.NumCPU -gt 1}In this example, the Where-Object cmdlet has a PowerShell scriptblock as a parameter. A scriptblock is a PowerShell script surrounded by braces. In this scriptblock, you see $_. When using commands in the pipeline, $_ represents the current object. In the preceding example, $_
