Vous êtes sur la page 1sur 26

vSphere PowerCLI Administration Guide

VMware vSphere PowerCLI 4.0

EN-000153-00

vSphere PowerCLI Administration Guide

You can find the most up-to-date technical documentation on the VMware Web site at: http://www.vmware.com/support/ The VMware Web site also provides the latest product updates. If you have comments about this documentation, submit your feedback to: docfeedback@vmware.com

2009 VMware, Inc. All rights reserved. This product is protected by U.S. and international copyright and intellectual property laws. VMware products are covered by one or more patents listed at http://www.vmware.com/go/patents. VMware, the VMware boxes logo and design, Virtual SMP, and VMotion are registered trademarks or trademarks of VMware, Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks of their respective companies.

VMware, Inc. 3401 Hillview Ave. Palo Alto, CA 94304 www.vmware.com

VMware, Inc.

Contents

AboutThisBook

1 GettingStartedwithvSpherePowerCLI 7
IntroductiontothevSpherePowerCLICmdlets CommandLineSyntax 7 LaunchingvSpherePowerCLI 8 ListAllvSpherePowerCLICmdlets 8 DisplayingHelpforAnyCmdlet 8 ConnectingtoaServer 8 7

2 BasicCmdletUsage 11
PowerShellCmdletUsage 11 Pipelines 11 Wildcards 11 CommonParameters 12 vSpherePowerCLISpecificCmdletUsage 12 TheServerParameter 12 SpecifyingObjects 12 ExamplesofBasicUsageofthevSpherePowerCLICmdlets 13 ConnectingtoaServer 13 BasicVirtualMachinesOperations 13 BasicVirtualMachineHostsOperations 14

3 AdvancedCmdletUsage 15
ExamplesofAdvancedCmdletUsage 15 UsingthevSpherePowerCLICmdlets 15 CreatevSphereObjects 15 UseVirtualMachineTemplates 16 CreateVirtualMachinesUsinganXMLSpecificationFile 17 CreateSnapshots 17 RemovevSphereObjects 18 UpdatetheResourceConfigurationSettingsofaVirtualMachine 18 ListVariousVirtualMachineHostsandDisplayingTheirProperties 18 ChangetheHostAdvancedConfigurationSettings 19 MigrateaVirtualMachine 19 UseVirtualMachineHostProfiles 20 ManageStatisticsandStatisticsIntervals 21 WebServiceAccessCmdlets 21 FiltervSphereObjects 22 PopulateaViewObject 22 UpdatetheStateofaServerSideObject 22 MixedUsageofvSpherePowerCLIandWebServiceAccessCmdlets 23 TheInventoryProvider 23 BasicFunctionsoftheInventoryProvider 23 TheDatastoreProvider 24 BasicfunctionsoftheDatastoreProvider 25

VMware, Inc.

vSphere PowerCLI Administration Guide

VMware, Inc.

About This Book

ThevSpherePowerCLIAdministrationGuideprovidesinformationaboutusingtheVMwarevSpherePowerCLI cmdlets(pronouncedcommandlets)setthatshipswithvSpherePowerCLIformanaging,monitoring, automating,andhandlinglifecycleoperationsforVMwarevSpherecomponentsvirtualmachines, datacenters,storage,networks,andsoon.

Intended Audience
ThisbookisintendedforanyonewhoneedstousevSpherePowerCLI.Theinformationinthisbookiswritten foradministratorswhoarefamiliarwithvirtualmachinetechnologyandWindowsPowerShell.Therearetwo categoriesofusersforvSpherePowerCLI:

BasicadministratorscanusePowerShellcommandsincludedinvSpherePowerCLItomanagetheir VMwareinfrastructurefromthecommandline. AdvancedadministratorscandevelopPowerShellscriptsthatmaybereusedbyotheradministratorsor integratedintootherapplications.

NOTEAllvSpherePowerCLIusersareexpectedtobefamiliarwiththedetailsofVMwarevSphere administrationandtheWindowsoperatingsystem.Solutiondevelopersareexpectedtobefamiliarwiththe .NETinfrastructureandtheVIMobjectmodelaswell.

Document Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentation.Ifyouhavecomments,sendyour feedbacktodocfeedback@vmware.com.

Technical Support and Education Resources


Thefollowingsectionsdescribethetechnicalsupportresourcesavailabletoyou.Toaccessthecurrentversion ofthisbookandotherbooks,gotohttp://www.vmware.com/support/pubs.

Online and Telephone Support


Touseonlinesupporttosubmittechnicalsupportrequests,viewyourproductandcontractinformation,and registeryourproducts,gotohttp://www.vmware.com/support. Customerswithappropriatesupportcontractsshouldusetelephonesupportforthefastestresponseon priority1issues.Gotohttp://www.vmware.com/support/phone_support.html.

Support Offerings
TofindouthowVMwaresupportofferingscanhelpmeetyourbusinessneeds,goto http://www.vmware.com/support/services.

VMware, Inc.

vSphere PowerCLI Administration Guide

VMware Professional Services


VMwareEducationServicescoursesofferextensivehandsonlabs,casestudyexamples,andcoursematerials designedtobeusedasonthejobreferencetools.Coursesareavailableonsite,intheclassroom,andlive online.Foronsitepilotprograms andimplementationbestpractices,VMwareConsultingServicesprovides offeringsto helpyouassess,plan,build,andmanageyourvirtualenvironment.Toaccessinformationabout educationclasses,certificationprograms,andconsultingservices,gotohttp://www.vmware.com/services.

VMware, Inc.

Getting Started with vSphere PowerCLI

vSpherePowerCLIprovideseasytouseC#andPowerShellinterfacetoVMwarevSphereAPIs.Itshipswith anumberofcmdletsthatyoucanusetoperformvariousadministrationtasksonVMwarevSphere components.ThischapterexplainshowtogetstartedusingthevSpherePowerCLIcmdlets. Thischaptercoversthefollowingtopics:


IntroductiontothevSpherePowerCLICmdletsonpage 7 LaunchingvSpherePowerCLIonpage 8

Introduction to the vSphere PowerCLI Cmdlets


MicrosoftPowerShellisbothacommandlineandscriptingenvironment,designedforWindows.Itleverages the.NETobjectmodelandprovidesadministratorswithmanagementandautomationcapabilities.Working withPowerShell,likewithanyotherconsoleenvironment,isdonebytypingcommands.InPowerShell commandsarecalledcmdlets,whichtermwewillusethroughoutthisguide. vSpherePowerCLI4.0shipswith165cmdlets:

163PowerShellbasedcmdlets. 2.NETcmdletsforusethroughPowerShellthesocalledWebServiceAccessCmdlets.SeeWebService AccessCmdletsonpage 21.

vSpherePowerCLIcmdletsarecreatedtoanswerthespecificneedsoftheVMwarevSphereadministration andmanagement.ThevSpherePowerCLIcmdletsarefoundintheVMware.VimAutomation.Coresnapin.

Command-Line Syntax
vSpherePowerCLIcommandlinesyntaxisthesameasgenericPowerShellsyntax. PowerShellcmdletsuseaconsistentverbnounstructure,wheretheverbspecifiestheactionandthenoun specifiestheobjecttooperateon.PowerShellcmdletsfollowconsistentnamingpatterns,whichmakesiteasy tofigureouthowtoconstructacommandifyouknowtheobjectyouwanttoworkwith. Allcommandcategoriestakeparametersandarguments.Aparameterstartswithahyphenandisusedto controlthebehaviorofthecommand.Anargumentisadatavalueconsumedbythecommand. AsimplePowerShellcommandlookslikethefollowing:
command -parameter1 -parameter2 argument1 -argument2

VMware, Inc.

vSphere PowerCLI Administration Guide

Launching vSphere PowerCLI


TolaunchvSpherePowerCLIfromtheStartmenu,clickPrograms>VMware>VMwarevSpherePowerCLI> VMwarevSpherePowerCLI. ThescriptconfigurationfileInitialize-VIToolkitEnvironment.ps1isloadedautomatically.Thisfileis locatedintheScriptsfolderinthevSpherePowerCLIinstallationdirectory.Administratorscaneditand extendthescripttodefinecmdletsaliases,configuretheenvironment,orsetvSpherePowerCLIstartup actions. NOTEInsteadoflaunchingthevSpherePowerCLIconsole,administratorscanalsoaccessthevSphere PowerCLIsnapindirectlyfromothertools,likePowerShellPlusorPowerGUI,byrunning:
Add-PSSnapin VMware.VimAutomation.Core

Inthiscase,theInitialize-VIToolkitEnvironment.ps1 scriptconfigurationfileisnotstarted automatically.Toloadit,typeitsnameintheconsolewindowwithoutspecifyingthepath:


Initialize-VIToolkitEnvironment.ps1

LoadingthefileprovidesaccesstovSpherePowerCLIcmdletsaliases,likeGet-VC,Get-ESX, andtoother configurationsettings.

List All vSphere PowerCLI Cmdlets


IfyouarenewtovSpherePowerCLI,onethingyouwanttoknowiswhatcmdletsareavailabletoyou.Toget alistofallvSpherePowerCLIcmdlets,usetheGet-Commandcmdletwiththe-PSSnapinparameterinthe followingway:
Get-Command -PSSnapin VMware.VimAutomation.Core

ThevSpherePowerCLIcmdletsarelistedintheconsolewindowasonelong,scrollingtopic.Youcanview themasinglepageatatimebypipingtheresultsoftheGet-Commandcmdlettothemoreoptioninthe followingway:


Get-Command -PSSnapin VMware.VimAutomation.Core | more

Displaying Help for Any Cmdlet


YoucangethelpforaspecificcmdletbysupplyingtheGet-HelpcommandinthevSpherePowerCLIConsole. Forexample,forinformationontheAdd-VMHostcmdlet,runtheGet-Helpcommandasfollows:
Get-Help Add-VMHost

Formoredetailedinformation,addthe-fullparameter:
Get-Help Add-VMHost -full

Alternatively,youcanusethehelpaliaswithanycmdlet:
help Add-VMHost

Toviewdetailedhelpinformationpagebypage,pipethehelpcmdlettothemorecmdlet:
help Add-VMHost -full | more

Connecting to a Server
TorunspecificvSpherePowerCLIcmdletsandperformadministrationormonitoringtasks,firstestablisha connectiontoanESXoravCenterServer. InthevSpherePowerCLIconsolewindow,typethefollowingcmdlet:
Connect-VIServer -Server <Server_Address>

where<Server_Address>istheIPaddressorDNSnameofthevCenterServerorESXhost.Whenprompted, enteryourusernameandpasswordtoauthenticatewiththeserver.

VMware, Inc.

Chapter 1 Getting Started with vSphere PowerCLI

Anotherwayistoputallinformationonthecommandlineatonce,usingtheProtocol,User,andPassword parameters.Forexample:
Connect-VIServer -Server 192.168.10.10 -Protocol http -User admin -Password sck9p84

Afteraconnectionisestablished,youarereadytorunthevSpherePowerCLIcmdlets. Forexample,youcanstartaspecificvirtualmachineusingthefollowingcmdlet:
Get-VM -name <virtual_machine_name> | Start-VM

Forexample,torunavirtualmachinenamedMyVM,run:
Get-VM -name MyVM | Start-VM

VMware, Inc.

vSphere PowerCLI Administration Guide

10

VMware, Inc.

Basic Cmdlet Usage

ThischapterexploresthebasicsofthevSpherePowerCLIcmdletsusage. Thechapterdiscussesthefollowingtopics:

PowerShellCmdletUsageonpage 11 ExamplesofBasicUsageofthevSpherePowerCLICmdletsonpage 13

NOTEThischapterdoesnotdiscussPowerShellbasics.YouareexpectedtohaveknowledgeofPowerShell anditscommandlineandscriptingconventions.

PowerShell Cmdlet Usage


Inthissection,someofthecmdletssyntaxandusagebasicconceptsaredescribed.

Pipelines
Apipelineisaseriesofcommandsseparatedbythepipeoperator|.Eachcommandinthepipelinereceives anobjectfromthepreviouscommand,performssomeoperationonit,andthenpassesitalongtothenext commandinthepipeline.Objectsareoutputfromthepipelineassoonastheybecomeavailable.Youcantype apipelineonasingleline,orspreaditacrossmultiplelines.Youcancyclebackwardsthroughcommand historyusingtheuparrow,soitiseasiertorepeatpipelinesifyoutypethemonasingleline.

Wildcards
PowerShellhasanumberofpatternmatchingoperatorscalledwildcards,whichworkonstrings.Forexample, todisplayallfileswitha.txtextension,run:
dir *.txt

Inthisexample,theasterisk*operatormatchesanycombinationofcharacters. Wildcardpatternsallowyoutospecifycharacterrangesaswell.Forexample,todisplayallfilesthatstartwith theletterSorTandhavea.txtextension,run:


dir [st]*.txt

Youcanusethequestionmark?wildcardtomatchanysinglecharacterwithinasequenceofcharacters.For example,todisplayall .txtfileswhosenamesconsistofstringandonemorecharacterintheend,run:


dir string?.txt

AllwildcardexpressionscanbeusedwiththevSpherePowerCLIcmdlets.

VMware, Inc.

11

vSphere PowerCLI Administration Guide

Common Parameters
TheWindowsPowerShellengineimplementsasetofreservedparameternames,referredtoascommon parameters.AllPowerShellcmdlets,includingthevSpherePowerCLIcmdlets,supportthem.Common parametersare:Verbose,Debug,ErrorAction,ErrorVariable,OutVariable,andOutBuffer. Respectively,thefollowingaliasesarereservedfortheseparameters:vb,db, ea,ev,ov,andob. Inaddition,therearetworiskmitigationparametersinPowerShell:WhatIfandConfirm.Whatifisused whenyouwanttoseetheeffectsofacommandwithoutexecutingit.Confirmisusedwhenacmdletperforms anoperationthatstopsaprogramorserviceordeletesdata. Formoredetailsontheusageofcommonparameters,usethefollowingcommand:
Get-Help about_CommonParameters

vSphere PowerCLI Specific Cmdlet Usage


ThissectionexploressomespecificconceptsofthevSpherePowerCLIcmdlets.

The Server Parameter


Bydefault,vSpherePowerCLIcmdletsareexecutedusingtheserverconnectionstoredinthe $DefaultVIServervariable.ThisvariablecontainsthelatestconnectionestablishedtoanESXhostor vCenterServer.ToapplyvSpherePowerCLIcmdletsonotherservers,administratorscanusetheServer parameter.,whichiscommonformostofthevSpherePowerCLIcmdlets.

Specifying Objects
InvSpherePowerCLI,allparametersthattakeasargumentsinventoryobjects(Cluster,Datacenter, Folder,ResourcePool,Template,VirtualMachine,VMHost),datastores,orOSCustomizationSpecobjects canbespecifiedbystringsandwildcards.ThisiscalledObjectbyNameselection(OBN).Ifaprovidedobject nameisnotrecognized,anOBNfailureoccurs.Insuchcases,anonterminatingerrorisgeneratedandthe cmdletisexecutedignoringtheinvalidname. Example 2-1. An OBN Failure
Set-VM VM VM1, VM2, VM3 Server $server1, $server2 MemoryMB 512

IftheVM2virtualmachinedoesnotexistoneitherofthespecifiedservers,anonterminatingerroristhrown andthecommandisappliedonlyontheVM1andVM2virtualmachines. FormoredetailsonOBN,usethefollowingcommand: help about_OBN Insteadofassigninganobjectnametoacmdletparameter,userscanpasstheobjectthroughapipelineora variable. NOTEInvSpherePowerCLI,passingstringsaspipelineinputisnotsupported. Forexample,thefollowingthreelinesareinterchangeable:


Remove-VM -VM "Win XP SP2" Get-VM -Name "Win XP SP2" | Remove-VM Remove-VM -VM (Get-VM -Name "Win XP SP2")

12

VMware, Inc.

Chapter 2 Basic Cmdlet Usage

Examples of Basic Usage of the vSphere PowerCLI Cmdlets


ThissectionprovidessomeexamplesofbasicvSpherePowerCLIcmdletsusage.

Connecting to a Server
Thefollowingcmdletestablishesaconnectiontoalocalserverandasksforcredentials(usernameand password),astheyarenotpassedasparameters:
Connect-VIServer -Server <VI_server_address>

Forexample:
Connect-VIServer -Server esx3.example.com

NOTEIfaproxyserverisusedfortheconnection,theadministratorshouldverifythatitisconfigured properly,sothattheconnectioniskeptalivelongenoughnottobreakthelongrunningvSpherePowerCLI tasks.Toremoveaproxy,runthefollowingcommand:


Set-VIToolkitConfiguration -ProxyPolicy NoProxy

Basic Virtual Machines Operations


Thefollowingscenarioshowshowtoretrieveinformationofavailablevirtualmachinesandtheiroperation system.ItalsodemonstrateshowtoshutdownavirtualmachineguestOSandtopoweroffthevirtual machineusingvSpherePowerCLIcmdlets. To manage virtual machines 1 Afterestablishingaconnectiontoaserver,listallvirtualmachinesonthetargetsystem:
Get-VM

SavethenameandthepowerstatepropertiesofthevirtualmachinesinthemyPoolresourcepoolintoa filenamedmyVMProperties.txt:
$pool = Get-ResourcePool myPool Get-VM -Location $pool | Select-Object Name, PowerState > myVMProperties.txt

StarttheMyVMvirtualmachine:
Get-VM "myVM" | Start-VM

RetrieveinformationoftheguestOSofthemyVM virtualmachine:
Get-VMGuest myVM | fc

ShutdowntheOSofthemyVMvirtualmachine:
Shutdown-VMGuest "myVM"

PoweroffthemyVMvirtualmachine:
Stop-VM "myVM"

MovethevirtualmachinemyVMfromtheABChosttotheXYZhost:
Get-VM -Name myVM -Location (Get-VMHost ABC) | Move-VM Destination (Get-VMHost XYZ)

NOTEIfthevirtualmachinetobemovedacrosshostsispoweredon,itmustbelocatedonasharedstorage registeredasadatastoreonboththeoriginalandthenewhost.

VMware, Inc.

13

vSphere PowerCLI Administration Guide

Basic Virtual Machine Hosts Operations


Thefollowingexamplescenarioillustratessomebasicoperationswithvirtualmachinehosts,likeaddinga hosttoavCenterServer,puttingahostintomaintenancemode,shuttingdown,andremovingahostfromthe vCenterServer. To manage virtual machine hosts 1 ListallhostsonthetargetVMwarevSphereserveryouhaveestablishedaconnectionwith:
Get-VMHost

AddastandalonevirtualmachinehosttothevCenterServer:
Add-VMHost -Name myHost -Location (Get-Datacenter Main) -User root -Password pass

ActivatemaintenancemodeforthemyHostvirtualmachinehost:
Get-VMHost myHost | Set-VMHost -State maintenance

RemovethemyHostvirtualmachinehostfrommaintenancemode:
Get-VMHost myHost | Set-VMhost -State connected

ShutdownthemyHostvirtualmachinehost
$host = Get-VMHost myHost $hv = Get-View $h.ID $hv.ShutdownHost_Task($true)

RemovethemyHostvirtualmachinehostwithoutconfirmation:
Remove-VMHost $host -Confirm:$false

14

VMware, Inc.

Advanced Cmdlet Usage

ThischapterprovidesexamplesofadvancedusageofthevSpherePowerCLIcmdlets. Thechapterdiscussesthesetopics:

ExamplesofAdvancedCmdletUsageonpage 15 TheInventoryProvideronpage 23 TheDatastoreProvideronpage 24

Examples of Advanced Cmdlet Usage


ThissectioncontainsexamplesofusingthevSpherePowerCLIcmdlets,theWebServiceAccesscmdlets,and theinventoryproviderfunctionalityforretrievingandmanagingVMwarevSphereobjects.

Using the vSphere PowerCLI Cmdlets


ThefollowingexamplesillustratehowtouseadvancedfunctionalityprovidedbythevSpherePowerCLIcmdlets:

Create vSphere Objects


Thefollowingscenarioillustratescommonmethodsforcreatingfolders,datacenters,clusters,resourcepools andvirtualmachinesusingvSpherePowerCLIcmdlets. To create inventory objects 1 EstablishaconnectiontoavCenterserver,usetheConnect-VIServercommand:
Connect-VIServer -Server <Server_Address>

Forexample:
Connect-VIServer -Server 192.168.10.10

Whenprompted,providetheadministratorsusernameandpasswordtoauthenticateaccessontheserver. 2 GettheinventoryrootfolderandcreateanewfoldercalledUSAinit:
$usaFolder = Get-Folder -NoRecursion | New-Folder -Name USA

Notethattheinformationaboutthelocationofthenewfolderisspecifiedthroughthepipeline. 3 CreateanewdatacentercalledOrlandoDCintheUSAfolder:
New-Datacenter -Location $usaFolder -Name OrlandoDC

CreateafoldercalledEngineeringunderOrlandoDC:
Get-Datacenter OrlandoDC | New-Folder -Name Engineering $engineeringFolder = Get-Folder -Name Engineering

NOTESearchinPowerShellisnotcasesensitive.
VMware, Inc. 15

vSphere PowerCLI Administration Guide

CreateanewclusterResearchAndDevelopmentCluster intheEngineeringfolder:
New-Cluster -Location $engineeringFolder -Name ResearchAndDevelopmentCluster -DrsEnabled -DrsAutomationLevel FullyAutomated

NOTEDrs(distributedresourcescheduler)isafacilitythatallowsautomaticallocationofclusterresources. 6 AddahostintheclusterusingtheAdd-VMHostcommand,whichpromptsyouforcredentials:
$hostInCluster1 = Add-VMHost -Name <host IP address> -Location ( Get-Cluster ResearchAndDevelopmentCluster )

TheparenthesesinterpolatetheobjectreturnedbytheGet-ClustercommandintoLocationparameter. 7 Createaresourcepoolintheclustersrootresourcepool:
$clusterRootRP = Get-ResourcePool -Location ( Get-Cluster ResearchAndDevelopmentCluster ) -Name Resources New-ResourcePool -Location $clusterRootRP -Name DevelopmentResources -CpuExpandableReservation $true -CpuReservationMhz 500 -CpuSharesLevel high -MemExpandableReservation $true -MemReservationMB 500 -MemSharesLevel high

Createavirtualmachinesynchronously:
New-VM -Name DevelopmentVM1 -VMHost $hostInCluster1 -ResourcePool ( Get-ResourcePool DevelopmentResources ) -DiskMB 4000 -MemoryMB 256

Createavirtualmachineasynchronously:
$vmCreationTask = New-VM -Name DevelopmentVM2 -VMHost $hostInCluster1 -ResourcePool (Get-ResourcePool DevelopmentResources) -DiskMB 4000 -MemoryMB 256 -RunAsync

The-RunAsyncparameterspecifiesthatthecommandwillbeexecutedasynchronously.Thismeansthat incontrasttoasynchronousoperation,youdonothavetowaitfortheprocesstocompletebefore supplyingthenextcommandinthecommandline.

Use Virtual Machine Templates


Avirtualmachinetemplateisareusableimagecreatedfromavirtualmachine.Thetemplate,asaderivative ofthesourcevirtualmachine,includesvirtualhardwarecomponents,aninstalledguestoperatingsystem,and softwareapplications. Thisprocedureillustrateshowtocreatevirtualmachinestemplatesandconvertthemtovirtualmachines. It usestheVMwarevSphereobjectscreatedinthepreviousexample. To create and use virtual machine templates 1 Addanadditional2GBharddisktotheDevelopmentVM2virtualmachine:
$vmCreationTask | Wait-Task | New-HardDisk -CapacityKB ( 2 * 1024 * 1024 )

CreateatemplatefromtheDevelopmentVM1virtualmachine:
New-Template -VM DevelopmentVM1 -Name WebTemplate -Location (Get-Datacenter orlandoDC )

NOTENotethatonVirtualCenter2.0andVirtualCenter2.5,thevirtualmachinemustbepoweredoffbefore creatingatemplatebasedonit.OnVirtualCenter2.5Update2,thevirtualmachinecanbepoweredoffor poweredon,butnotsuspended. 3 ConvertthistemplateforausebyavirtualmachinenamedDevelopmentVM3:


Get-Template WebTemplate | Set-Template -ToVM -Name DevelopmentVM3

CreateatemplatefromtheDevelopmentVM2virtualmachine:
New-Template -VM DevelopmentVM2 -Name DatabaseTemplate -Location (Get-Datacenter orlandoDC )

ConvertthistemplatetoavirtualmachinenamedDevelopmentVM4:
Get-Template DatabaseTemplate | Set-Template -ToVM -Name DevelopmentVM4

16

VMware, Inc.

Chapter 3 Advanced Cmdlet Usage

MovethevirtualmachinesintotheDevelopmentResourcesresourcepool:
Get-VM DevelopmentVM? | Move-VM -Destination ( Get-ResourcePool DevelopmentResources )

Use?asawildcardtomatchjustonesymbol.Thecommandreturnsallvirtualmachineswhosenames startwithDevelopmentVMandhaveonemoresymbolattheend.Inthisexample,DevelopmentVM1, DevelopmentVM2,DevelopmentVM3,andDevelopmentVM4areretrievedandmovedintothe DevelopmentResourcesresourcepool. 7 StartthevirtualmachinesintheDevelopmentResourcesresourcepool:


Get-ResourcePool DevelopmentResources | Get-VM | Start-VM

Create Virtual Machines Using an XML Specification File


Thisexampleillustrateshowtocreatevirtualmachinesinaccordancewiththespecificationprovidedinan XMLfile. ConsideramyVM.xml file,withthefollowingcontent:
<CreateVM> <VM> <Name>DevelopmentVM1</Name> <HDDCapacity>10000</HDDCapacity> </VM> <VM> <Name>DevelopmentVM2</Name> <HDDCapacity>10000</HDDCapacity> </VM> </CreateVM>

ToreadthecontentofthemyVM.xmlfile,run:
[xml]$s = Get-Content myVM.xml

Tocreatethevirtualmachines,run:
$s.CreateVM.VM | where { New-VM -VMHost 192.168.10.11 -Name $_.Name -Disk MB $_.HDDCapacity}

Create Snapshots
Asnapshotcapturesthememory,disk,andsettingsstateofavirtualmachineataparticularmoment.When youreverttoasnapshot,youreturnalltheseitemstothestatetheywereinatthetimeyoutookthatsnapshot. Thefollowingprocedureillustratestakingasnapshotofvirtualmachinesandthenrevertingthevirtual machinestoit. To create and use snapshots 1 TakeasnapshotofallvirtualmachinesintheDevelopmentResourcesresourcepool:
Get-ResourcePool DevelopmentResources | Get-VM | New-Snapshot -Name InitialDevConfig

The-LocationparametertakesargumentsoftheVIContainertype,onwhichCluster,Datacenter, Folder,ResourcePool,andVMHostobjecttypesarebased.Therefore,the-Locationparametercanuse argumentsofallthesetypes. 2 RevertallvirtualmachinesintheDevelopmentResourcesresourcepooltotheInitialDevConfig snapshot:


$VMs = Get-VM -Location ( Get-ResourcePool DevelopmentResources ) foreach( $vm in $VMs ) { Set-VM -VM $vm -Snapshot ( Get-Snapshot -VM $vm -Name InitialDevConfig ) }

VMware, Inc.

17

vSphere PowerCLI Administration Guide

Remove vSphere Objects


ThisprocedureillustrateshowtoremovesomeoftheVMwarevSphereobjectscreatedinthepreviousexamples. To remove inventory objects 1 Retrievethevirtualmachinesusingthe?wildcardsymbolintheNameparameterandremovethem alongwiththeirdisks:
Get-VM DevelopmentVM? | Remove-VM -DeleteFromDisk

RemovetheUSAfolder:
Remove-Folder -Folder ( Get-Folder usa )

ByexecutingtheRemove-Foldercommand,allchildobjectsforthefolderdatacenters,folders,clusters, hosts,resourcepools,andsoonarealsoremoved.

Update the Resource Configuration Settings of a Virtual Machine


Thefollowingprocedureillustrateshowtoretrieveandmodifytheresourceconfigurationpropertiesofa virtualmachine. To update the resource configuration of a virtual machine 1 EstablishaconnectiontoanESXihostbytheConnect-VIServercommand:
Connect-VIServer -Server <Server_Address>

RetrievetheresourceconfigurationfortheVM1virtualmachine.:
Get-VMResourceConfiguration -VM ( Get-VM VM1 )

DisplaythediskshareoftheVM1virtualmachine:
Get-VMResourceConfiguration -VM ( Get-VM VM1 ) | Format-Custom -Property DiskResourceConfiguration

ChangethememoryshareoftheVM1virtualmachinetolow:
Get-VM VM1 | Get-VMResourceConfiguration | Set-VMResourceConfiguration -MemSharesLevel low

UpdatetheCPUshareoftheVM1virtualmachinetohigh:
Get-VM VM1 | Get-VMResourceConfiguration | Set-VMResourceConfiguration -CpuSharesLevel high

ChangethediskshareoftheVM1virtualmachineto100:
$vm = Get-VM VM1 $disk = Get-HardDisk $vm Get-VMResourceConfiguration $vm | Set-VMResourceConfiguration -Disk $disk -DiskSharesLevel custom -NumDiskShares 100

List Various Virtual Machine Hosts and Displaying Their Properties


Thisscenarioillustrateshowtolistallavailablevirtualmachinehostsinadatacenteranddisplaytheirproperties. To list the available hosts and display their properties 1 ListallvirtualmachinehoststhatarepartofthedatacenternamedCaliforniaDC:
Get-Datacenter CaliforniaDC | Get-VMHost | Format-Custom

Displaythepropertiesofthefirstvirtualmachinehostinthedatacenter:
Get-Datacenter CaliforniaDC | Get-VMHost | Select-Object -First 1 | Get-View | Format-Custom

DisplaystheNameandtheOverallStatuspropertiesofthevirtualmachinehostsintheCaliforniaDC datacenter:
Get-Datacenter CaliforniaDC | Get-VMHost | Get-View | Format-Table -Property Name,OverallStatus -AutoSize

18

VMware, Inc.

Chapter 3 Advanced Cmdlet Usage

Displayallvirtualmachinehostsandtheirproperties,andsavetheresultstoafile:
Get-Datacenter CaliforniaDC | Get-VMHost | Get-View | Format-Custom | Out-File FilePath hosts.txt

ListthevirtualmachinehoststhatareinmaintenancemodeandcanbeconfiguredforVMotion operations:
Get-VMHost -State maintenance | Get-View | Where-Object -FilterScript { $_.capability -ne $null -and $_.capability.vmotionSupported }

Change the Host Advanced Configuration Settings


Thisprocedureshowshowtomigratevirtualmachinesfromonevirtualmachinehosttoanother. To change the host advanced configuration settings 1 ChangethemigrationtimeoutfortheMyESXHost1virtualmachinehost:.
Get-VMHost MyESXHost1 | Set-VmHostAdvancedConfiguration -Name Migrate.NetTimeout -Value ( [system.int32] 10 )

Enablemakingchecksumofthevirtualmachinesmemoryduringthemigration:
Get-VMHost MyESXHost | Set-VmHostAdvancedConfiguration -Name Migrate.MemChksum -Value ( [system.int32] 1 )

GettheMyESXHost1virtualmachinehostmigrationsettings:
$migrationSettings = Get-VMHost MyESXHost1| Get-VmHostAdvancedConfiguration -Name Migrate.*

ApplythemigrationsettingstoMyESXHost2:
Set-VmHostAdvancedConfiguration -VMHost ( Get-VMHost MyESXHost2 ) -Hashtable $migrationSettings

Migrate a Virtual Machine


Thefollowingproceduresillustratehowtomigrateavirtualmachinebetweenhostsanddatastoresusingthe VMotionandStorageVMotionfeatures. To move a virtual machine using VMotion 1 EstablishaconnectiontoaserverusingtheConnect-VIServercommand:
Connect-VIServer -Server <Server_Address>

RetrievetheVM1virtualmachineandmoveittothehostnamedEsxHost2:
Get-VM VM1 | Move-VM -Destination ( Get-VMHost EsxHost2 )

NOTEVMotionallowstomoveavirtualmachinethatispoweredonfromonehosttoanother.Thevirtual machinemustbestoredonadatastoresharedbythecurrentanddestinationhosts,andtheVMotioninterfaces onthetwohostsmustbeproperlyconfigured. To move a virtual machine using Storage VMotion 1 EstablishaconnectiontoaserverusingtheConnect-VIServercommand:
Connect-VIServer -Server <Server_Address>

RetrievetheVM1virtualmachineandmoveittothedatastorenamedDatastore2:
Get-VM VM1 | Move-VM -Datastore ( Get-Datastore Datastore2 )

NOTEStorageVMotionallowstomoveavirtualmachinethatispoweredonfromonedatastoretoanother. Thehostonwhichthevirtualmachineisrunningmusthaveaccessbothtothedatastorewherethevirtual machineislocatedandtothedestinationdatastore.

VMware, Inc.

19

vSphere PowerCLI Administration Guide

Use Virtual Machine Host Profiles


Thisscenarioillustrateshowtogetuseofthevirtualmachinehostprofiles. To create and apply host profiles 1 EstablishaconnectiontoaserverusingtheConnect-VIServercommand:
Connect-VIServer -Server <Server_Address>

TheservermustbevCenter4.0orlater.Earlierreleasesdonotsupporthostprofiles. 2 GetthevirtualmachinehostnamedMyHost01andstoreitinthe$hvariable:
$h = Get-VMHost MyHost01

CreateaprofilebasedontheMyHost01virtualmachinehost:
New-VMHostProfile -Name testProfile -Description "This is my test host profile." -ReferenceHost $h

Getthenewlycreatedvirtualmachinehostprofile:
$p = ( Get-VMHostProfile -Name testProfile )[0]

ChangethedescriptionofthetestProfilehostprofile:
Set-VMHostProfile -Profile $p -Description "This is my test virtual machine host profile."

GettheMyHost02virtualmachinehost,onwhichtoapplythetestProfilevirtualmachinehostprofile:
$applyHost = Get-VMHost MyHost02

AssociatetheMyHost02virtualmachinehostwiththetestProfilehostprofile:
Set-VMHost -VMHost $applyHost -Profile $p

TestiftheMyHost02hostiscompliantwiththetestProfile profile:
Test-VMHostProfileCompliance -VMHost $applyHost

Theoutputofthiscommandcontainsthehostsincompliantsettings,ifany. 9 ApplytheprofiletotheMyHost02host:
$neededVariables = Apply-VMHostProfile -Entity $applyHost -Profile $p -Confirm:$false

The$neededVariablesvariablecontainsthenamesofallrequiredvariablesandtheirdefaultorcurrent values,asreturnedbytheserver.Otherwise,the$neededVariablesvariablecontainsthenameofthe hostonwhichtheprofilehasbeenapplied. 10 ExportthetestProfileprofiletoafile:


Export-VMHostProfile -FilePath export.prf -Profile $p -Force

11

Importanewprofilefromtheexport.prf file:
Import-VMHostProfile -FilePath export.prf -Name importedProfile

12

Deletethecreatedprofiles:
Get-VMHostProfile -Name "testProfile","importedProfile" | Remove-VMHostProfile -Confirm:$false

20

VMware, Inc.

Chapter 3 Advanced Cmdlet Usage

Manage Statistics and Statistics Intervals


ThisexamplescenarioshowshowtousethevSpherePowerCLIcmdletstoretrieveandmanageinventory objectsstatistics. To create and manage statistics and statistics intervals 1 EstablishaconnectiontoaserverbyusingtheConnect-VIServercommand:
Connect-VIServer -Server <Server_Address>

TheservermusthaveVirtualCenter2.0orhigherinstalled.Earlierreleasesdonotsupportcreating statisticsintervals. 2 Createanewstatisticsintervalnamedminute:


New-StatsInterval -Name minute -SamplingPeriodSecs 60 -StorageTimeSecs 600

Createanotherstatisticsintervalnamedpast hour:
New-StatsInterval -Name "past hour" -SamplingPeriodSecs (60 * 60) -StorageTimeSecs 50000

NOTEThesamplingperiodofanewstatisticsintervalmustbeamultipleofthepreviousintervalsampling period. 4 Createathirdstatisticsintervalnamedpast day:


New-StatsInterval -Name "past day" -SamplingPeriodSecs ( 60 * 60 * 12 ) -StorageTimeSecs 500000

Extendthestoragetimeofthepast daystatisticsinterval:
Set-StatsInterval -Interval "past day" -StorageTimeSecs 700000

ListtheavailablememorymetrictypesfortheMyClustercluster:
$cluster = Get-Cluster MyCluster1 $statTypes = Get-StatType -Entity $cluster -Interval "past day" -Name mem.*

Listtheclusterstatisticscollectedfortheday:
Get-Stat -Entity $cluster -Start ([System.DateTime]::Now.AddDays(-1)) -Finish ([System.DateTime]::Now) -Stat $statTypes

Web Service Access Cmdlets


ThevSpherePowerCLI4.0listofcmdletsincludestwoWebServiceAccesscmdlets:

Get-View Get-VIObjectByVIView

TheyenableaccesstotheprogrammingmodelofthevSphereSDKfor.NETfromPowerShellandcanbeused toinitiatevSphere.NETobjects.Eachobject:

Isastaticcopyofaserversidemanagedobjectandisnotautomaticallyupdatedwhentheobjectonthe serverchanges. Includespropertiesandmethodsthatcorrespondtothepropertiesandoperationsoftheserverside managedobject.Formoreinformationaboutserversideobjectmethodsandproperties,checkthe VMwarevSphereAPIReferenceGuide(http://www.vmware.com/support/pubs/sdk_pubs.html).

UsingtheWebServiceAccesscmdletsforlowlevelVMwarevSpheremanagement requiressomeknowledge ofbothPowerShellscriptingandtheVMwarevSphereAPI.

VMware, Inc.

21

vSphere PowerCLI Administration Guide

Filter vSphere Objects


ThisprocedureillustratestheuseoftheGet-Viewcmdletincombinationwithafilter.Thefilterparameteris aHashTablecontainingoneormorepairsoffiltercriteria.Eachofthecriteriaconsistsofapropertypathand avaluethatrepresentsaregularexpressionpatternusedtomatchtheproperty. ThefilterinthisproceduregetsalistofthepoweredonvirtualmachineswhoseguestOSnamescontain WindowsXP.TheGetViewcmdlettheninitiatesshutdownforeachguestOSinthelist. To create and apply a filter 1 Createafilterbythepowerstateandtheguestoperatingsystemnameofthevirtualmachines:
$filter = @{"Runtime.PowerState" ="poweredOn"; "Config.GuestFullName" = "Windows XP"}

GetalistofthevirtualmachinesusingthecreatedfilterandcalltheShutdownGuestmethodforeach virtualmachineinthelist:
Get-View -ViewType "VirtualMachine" -Filter $filter | foreach{$_.ShutdownGuest()}

Populate a View Object


Thisprocedureillustrateshowtopopulateaviewobjectfromanalreadyretrievedmanagedobjectusingthe Get-Viewcmdlet. To populate a view object 1 Getthe Development2virtualmachineusingafilterbynameandpopulatestheviewobject.
$vm = Get-View -ViewType VirtualMachine -Filter @{"Name" = "DevelopmentVM2} $hostView = Get-View -Id $vm.Runtime.Host

Retrieveruntimeinformation:
$hostView.Summary.Runtime

Update the State of a Server-Side Object


Thisprocedureillustrateshowtoupdatethestateofserversideobjects. To update the state of a server-side object 1 GettheDevelopment2 virtualmachineusingafilterbyname:
$vm = Get-View -ViewType VirtualMachine -Filter @{"Name" = "DevelopmentVM2} $hostView = Get-View -Id $vm.Runtime.Host

Printthecurrentpowerstate:
$vm.Runtime.PowerState

Changethepowerstateofthevirtualmachine:
If ($vm.Runtime.PowerState -ne PoweredOn) { $vm.PowerOnVM($vm.Runtime.Host) } else { $vm.PowerOffVM() }

Printthevalueof$vmpowerstate(thepowerstateisstillnotupdatedbecausethevirtualmachine propertyvaluesarenotupdatedautomatically):
$vm.Runtime.PowerState

Updatetheview:
$vm.UpdateViewData()

Showtheactualpowerstateofthevirtualmachine:
$vm.Runtime.PowerState

22

VMware, Inc.

Chapter 3 Advanced Cmdlet Usage

Mixed Usage of vSphere PowerCLI and Web Service Access Cmdlets


TogetmoreadvantagesoftheusabilityandfunctionalityofthevSpherePowerCLIcmdletsandtheWeb ServiceAccesscmdletsyoucanusethemtogether. To reboot a virtual machine host 1 UsetheGet-VMHostcmdlettogetavirtualmachinehostbyitsname,andpasstheresulttotheGet-View cmdlettoretrievethehostview:
$hostView = Get-VMHost -Name "host.domain.com" | Get-View

host.domain.nameistheIPaddressortheDNSnameoftheESXhostasshownintheinventory. 2 Calltherebootmethodofthehostviewobjecttorebootthehost:
$hostView.RebootHost()

To modify the CPU levels of a virtual machine ThisexampleshowshowtomodifytheCPUlevelsofavirtualmachineusingcombinationoftheGet-View andGet-VIObjectByVIViewcmdlets. 1 RetrievetheDevelopment2virtualmachine,shutdownit,andpasstheresulttotheGet-Viewcmdletto retrievethevirtualmachineviewobject:
$vmView = Get-VM DevelopmentVM2 | Stop-VM | Get-View

CreateaVirtualMachineConfigSpecobjecttomodifythevirtualmachineCPUlevelsandcallthe ReconfigVMmethodofthevirtualmachineviewmanagedobject.
$spec = new-object VMware.Vim.VirtualMachineConfigSpec; $spec.CPUAllocation = New-Object VMware.Vim.ResourceAllocationInfo; $spec.CpuAllocation.Shares = New-Object VMware.Vim.SharesInfo; $spec.CpuAllocation.Shares.Level = "normal"; $spec.CpuAllocation.Limit = -1; $vmView .ReconfigVM_Task($spec)

GetavirtualmachineobjectbyusingtheGet-VIObjectByVIViewcmdletandstartthevirtualmachine.
$vm = Get-VIObjectByVIView $vmView | Start-VM

The Inventory Provider


TheInventoryProvider(VimInventory)isdesignedtoexposearawinventoryviewoftheinventoryitems fromaserver.ItenablesinteractivenavigationandfilestylemanagementoftheVMwarevSphereinventory. BycreatingaPowerShelldrivebasedonamanagedobject(suchasadatacenter),youobtainaviewofits contentsandtherelationshipsbetweentheitems.Inaddition,youareabletomanipulateobjects(move, renameordeletethem)byrunningcommandsfromthevSpherePowerCLIconsole.

Basic Functions of the Inventory Provider


Thefollowingprocedureillustratessomebasicfunctionsoftheinventoryprovider. To create and use a inventory drive 1 Establishaconnectiontotheserverusingthe Connect-VIServercommand:
Connect-VIServer -Server <Server_Address>

Forexample:
Connect-VIServer -Server 192.168.10.10

Whenprompted,providetheadministratorusernameandpasswordtoauthenticateaccessontheserver. 2 Gettherootfolderoftheserver:
$root = Get-Folder -NoRecursion

VMware, Inc.

23

vSphere PowerCLI Administration Guide

CreateaPowerShelldrivenamedVI,basedontheserverrootfolder.Youcanusethebuiltin New-psDrivecmdlet.
New-PSDrive -Location $root -Name vi -PSProvider VimInventory -Root '\'

NOTEInthisrelease,asinglebackslashistherequiredvalueforthe-Rootparameter. AdifferentwaytocreateainventorydriveistousetheNew-VIInventoryDrive command,whichisan aliasofNew-PSDrive.ItcreatesanewinventorydriveusingtheNameandLocationparameters. For example:


Get-Folder -NoRecursion | New-VIInventoryDrive -Name vi

Accessthenewdrivebyrunningthefollowingcommand:
cd vi:

Tolistthedrivecontent,run
dir

dirisanaliasoftheGet-ChildItemcmdlet. 5 Navigatethroughyourserverinventoryusingthecdcommandwiththefullpathtothehost.Fora fictionalVMwarevSphereinventory,itmightlooklikethefollowing:


cd Folder01\DataCenter01\host\Web\LiveHost01

Listthecontentofthehostusingthelscommand:
ls

lsistheUNIXstylealiasoftheGet-ChildItemcmdlet. Thiscommandwillreturnthevirtualmachinesandtherootresourcepoolofthehost.Toviewonlythe virtualmachinesofthehost,runthefollowingcmdlet:


Get-VM

Whencalledwithintheinventorydrive,Get-VMretrievesonlythevirtualmachinesonthecurrentdrive location. 7 DeleteavirtualmachinenamedLiveVm01:


del LiveVm01

RenameavirtualmachinefromLiveVm01NewtoLiveVm01:
ren LiveVm01New LiveVm01

StartallvirtualmachineswhosenamesstartwithLiveVm:
dir LiveVm* | Start-VM

NotethattheproviderfilestyleoperationsworkonthesameinventoryobjectsasthevSpherePowerCLI cmdlets.

The Datastore Provider


TheDatastoreProvider(VimDatastore)isdesignedtoprovideaccesstothecontentsofoneormore datastores.Theitemsinadatastorearefilesthatcontainconfiguration,virtualdisk,andtheotherdata associatedwithavirtualmachine.Allfileoperationsarecasesensitive. NOTEOnVirtualCenter2.0andESX3.0,DatastoreProvidersupportsonlybrowsinganddeletingitems. On VirtualCenter2.5andESX3.5,allfileoperationsareavailable,includingmoving,copying,andrenaming items.

24

VMware, Inc.

Chapter 3 Advanced Cmdlet Usage

Basic functions of the Datastore Provider


ThefollowingprocedureillustratessomebasicfunctionsoftheDatastoreProvider. To create and use a datastore drive 1 Establishaconnectiontotheserverusingthe Connect-VIServercommand:
Connect-VIServer -Server <Server_Address>

Forexample:
Connect-VIServer -Server 192.168.10.10

Whenprompted,providetheadministratorusernameandpasswordtoauthenticateaccessontheserver. 2 Getadatstorebyitsnameandassignittothe$datastorevariable.
$datastore = Get-Datastore Storage1

CreateaPowerShelldriveds:,basedon$datastore.YoucanusethebuiltinNew-PSDrivecmdlet.
New-PSDrive -Location $datastore -Name ds -PSProvider VimDatastore -Root '\'

AdifferentwaytocreateadatastoredriveistousetheNew-DatastoreDrive command,whichisanalias ofNew-PSDrive.ItcreatesanewdatastoredriveusingtheNameandDatastoreparameters.Forexample:


Get-Datastore Storage1 | New-DatastoreDrive -Name ds

Accessthenewdrivebyrunningthefollowingcommand:
cd ds:

Tolistthedrivecontent,run:
dir

dirisanaliasoftheGet-ChildItemcmdlet. 5 Navigatetoaspecificfolderonthe ds: drive,usingthecdcommand:


cd <Folder_Name>

ForafictionalVMwarevSphereinventory,thecommandmightlooklikethefollowing:
cd VirtualMachines\XPVirtualMachine

Listthefilesofthefolderusingthelscommand:
ls

lsistheUNIXstylealiasoftheGet-ChildItemcmdlet. 7 RenameafileusingtheRename-Itemcmdletoritsaliasren.Forexample,tochangethenameofthe vmware-3.logfiletovmware-3old.log, runthefollowingcommand:


ren vmware-3.log vmware-3old.log

Allfileoperationsapplyonlyonfilesinthecurrentfolder. 8 DeleteafileusingtheRemove-Item cmdletoritsaliasdel.Forexample,toremovethe vmware-3old.logfilefromtheXPVirtualMachinefolder,usethefollowingcommand: delds:\VirtualMachines\XPVirtualMachine\vmware2.log 9 CopyafileusingtheCopy-Itemcmdletoritsaliascopy.Forexample:


copy ds:\VirtualMachines\XPVirtualMachine\vmware-3old.log ds:\VirtualMachines\vmware-3.log

VMware, Inc.

25

vSphere PowerCLI Administration Guide

26

VMware, Inc.

Vous aimerez peut-être aussi