Académique Documents
Professionnel Documents
Culture Documents
EN-000153-00
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.
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.
VMware, Inc.
Intended Audience
ThisbookisintendedforanyonewhoneedstousevSpherePowerCLI.Theinformationinthisbookiswritten foradministratorswhoarefamiliarwithvirtualmachinetechnologyandWindowsPowerShell.Therearetwo categoriesofusersforvSpherePowerCLI:
Document Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentation.Ifyouhavecomments,sendyour feedbacktodocfeedback@vmware.com.
Support Offerings
TofindouthowVMwaresupportofferingscanhelpmeetyourbusinessneeds,goto http://www.vmware.com/support/services.
VMware, Inc.
VMware, Inc.
IntroductiontothevSpherePowerCLICmdletsonpage 7 LaunchingvSpherePowerCLIonpage 8
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.
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.
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.
10
VMware, Inc.
ThischapterexploresthebasicsofthevSpherePowerCLIcmdletsusage. Thechapterdiscussesthefollowingtopics:
PowerShellCmdletUsageonpage 11 ExamplesofBasicUsageofthevSpherePowerCLICmdletsonpage 13
NOTEThischapterdoesnotdiscussPowerShellbasics.YouareexpectedtohaveknowledgeofPowerShell anditscommandlineandscriptingconventions.
Pipelines
Apipelineisaseriesofcommandsseparatedbythepipeoperator|.Eachcommandinthepipelinereceives anobjectfromthepreviouscommand,performssomeoperationonit,andthenpassesitalongtothenext commandinthepipeline.Objectsareoutputfromthepipelineassoonastheybecomeavailable.Youcantype apipelineonasingleline,orspreaditacrossmultiplelines.Youcancyclebackwardsthroughcommand historyusingtheuparrow,soitiseasiertorepeatpipelinesifyoutypethemonasingleline.
Wildcards
PowerShellhasanumberofpatternmatchingoperatorscalledwildcards,whichworkonstrings.Forexample, todisplayallfileswitha.txtextension,run:
dir *.txt
AllwildcardexpressionscanbeusedwiththevSpherePowerCLIcmdlets.
VMware, Inc.
11
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
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
12
VMware, Inc.
Connecting to a Server
Thefollowingcmdletestablishesaconnectiontoalocalserverandasksforcredentials(usernameand password),astheyarenotpassedasparameters:
Connect-VIServer -Server <VI_server_address>
Forexample:
Connect-VIServer -Server esx3.example.com
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
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.
ThischapterprovidesexamplesofadvancedusageofthevSpherePowerCLIcmdlets. Thechapterdiscussesthesetopics:
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
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
CreateatemplatefromtheDevelopmentVM1virtualmachine:
New-Template -VM DevelopmentVM1 -Name WebTemplate -Location (Get-Datacenter orlandoDC )
CreateatemplatefromtheDevelopmentVM2virtualmachine:
New-Template -VM DevelopmentVM2 -Name DatabaseTemplate -Location (Get-Datacenter orlandoDC )
ConvertthistemplatetoavirtualmachinenamedDevelopmentVM4:
Get-Template DatabaseTemplate | Set-Template -ToVM -Name DevelopmentVM4
16
VMware, Inc.
MovethevirtualmachinesintotheDevelopmentResourcesresourcepool:
Get-VM DevelopmentVM? | Move-VM -Destination ( Get-ResourcePool DevelopmentResources )
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
VMware, Inc.
17
RemovetheUSAfolder:
Remove-Folder -Folder ( Get-Folder usa )
ByexecutingtheRemove-Foldercommand,allchildobjectsforthefolderdatacenters,folders,clusters, hosts,resourcepools,andsoonarealsoremoved.
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
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.
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 }
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
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 )
VMware, Inc.
19
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
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.
Createanotherstatisticsintervalnamedpast hour:
New-StatsInterval -Name "past hour" -SamplingPeriodSecs (60 * 60) -StorageTimeSecs 50000
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
Get-View Get-VIObjectByVIView
TheyenableaccesstotheprogrammingmodelofthevSphereSDKfor.NETfromPowerShellandcanbeused toinitiatevSphere.NETobjects.Eachobject:
VMware, Inc.
21
GetalistofthevirtualmachinesusingthecreatedfilterandcalltheShutdownGuestmethodforeach virtualmachineinthelist:
Get-View -ViewType "VirtualMachine" -Filter $filter | foreach{$_.ShutdownGuest()}
Retrieveruntimeinformation:
$hostView.Summary.Runtime
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.
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
Forexample:
Connect-VIServer -Server 192.168.10.10
Whenprompted,providetheadministratorusernameandpasswordtoauthenticateaccessontheserver. 2 Gettherootfolderoftheserver:
$root = Get-Folder -NoRecursion
VMware, Inc.
23
CreateaPowerShelldrivenamedVI,basedontheserverrootfolder.Youcanusethebuiltin New-psDrivecmdlet.
New-PSDrive -Location $root -Name vi -PSProvider VimInventory -Root '\'
Accessthenewdrivebyrunningthefollowingcommand:
cd vi:
Tolistthedrivecontent,run
dir
Listthecontentofthehostusingthelscommand:
ls
RenameavirtualmachinefromLiveVm01NewtoLiveVm01:
ren LiveVm01New LiveVm01
StartallvirtualmachineswhosenamesstartwithLiveVm:
dir LiveVm* | Start-VM
NotethattheproviderfilestyleoperationsworkonthesameinventoryobjectsasthevSpherePowerCLI cmdlets.
24
VMware, Inc.
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 '\'
Accessthenewdrivebyrunningthefollowingcommand:
cd ds:
Tolistthedrivecontent,run:
dir
ForafictionalVMwarevSphereinventory,thecommandmightlooklikethefollowing:
cd VirtualMachines\XPVirtualMachine
Listthefilesofthefolderusingthelscommand:
ls
VMware, Inc.
25
26
VMware, Inc.