Tuesday, December 22, 2009

vSphere PowerCLI Quick Start


vSphere Command-Line Interface vCLI or vSphere PowerCLI can be used to manage ESX/ESXi host.  vCLI is supported on  both Windows and Linux Client; PowerCLI is supported Windows Client only,  but it is more powerful than vCLI.

Windows PowerShell basics

 
###Windows Powershell supports wildcard
* ? []
###Window Powershell help
help
help get*
help get-vm
help get-vm -full

###list alias
get-alias
e.g

sort sort-object
ft format-table
fl format-list

###Variable, store result into variable
$var=get-process
#$var becomes array, $var[0] is first process, so it can be used in foreach loop for more complex operations
foreach ($proc in $var) {  $proc.ProcessName}
#The output  can be achieved by format-table
get-process | ft name

###sort, ascending is  default order
get-process| sort cpu -descending
###filter, find notepad process
get-process| where-object { $_.name -eq "notepad" }

vSphere PowerCLI basics


###Install in following order
- install Windows  PowerShell on Window XP/Windows 2003/Windows 2008.
- install vSphere PowerCLI

### First time use
#you will receive certificate warning,  type A to accept it for always run.
#after this you will receive the other  warning about signing,  type this command:
Set-ExecutionPolicy RemoteSigned.
#restart PowerCLI to check if warning disappears.

### Login and execute command
#login
Connect-VIServer -server ServerName
##Some useful commands

#list all vms and sort them by Memory in descending order
#The column real name is MemoryMB, but it is displayed as "Memory (MB)"
# So you need to use fl command to find out the realname ;
get-vm vmname | fl
get-vm | sort MemoryMB -descending

#Restart all VMs which are currently Poweredon
#Don't use Restart-VM  because it  is like poweron and poweroff, not #graceful restart
get-vm | where {$_.powerstate -eq "poweredon"} | reset-vmguest

#Read hosts from file
# if you want to exclude some hosts from previous example, you certainly # can add more filter expression but i just want to show how to read file,
#save output to a file
get-vm | where {$_.powerstate -eq "poweredon"}  >d:\temp\host.list

#Edit the file and remove unwanted hosts
#Read the file and restart all hosts in the file, trimend is to remove trailing space
get-content d:\temp\host.list | foreach { $x=$_.trimend() ; reset-vmguest  $x }

Links:
PowerShell quick reference
VBScript-to-Windows PowerShell Conversion Guide
VMware: vSphere PowerCLI Blog

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.