PowerCLI学习(1)
VMware vSphere PowerCLI包含了微软PowerShell的cmdlets,提供了C#和PowerShell访问控制VMware vSphere与vClould APIs的接口。通过它可以实现自动管理VMware环境。
一、Microsoft PowerShell简介
PowerShell是基于Windows的命令行与脚本环境,基于.NET对象模型,提供了对系统的管理和自动化功能。它主要包括:(1) Command-Line,即cmdlets;主要是Verb-Noun结构,Verb表示动作,N表示操作对象。(2) Pipelines,即管道|;它是由|隔开的一系列command;每个命令从前一个命令中获得一个结果对象,并对这个结果对象执行command,然后再将新的执行结果传给下一个command。(3) Wildcards,即通配符;eg, asterisk'*'可以匹配任何字符;question'?'可匹配任何单一字符;range‘[st]‘则会匹配以s或t开头的字符串。(4) Common Parameters,即参数,以hyphen'-'开始,用来控制command的行为。注意argument是提供过command的数据值。
eg,一个PowerShell命令的例子:
command -parameter1 -parameter2 argument1, argument2
所有的命令都可以Get-Help/get-help去需求帮助;eg, Get-Help about_parameters
WhatIf---不运行命令先显示effects
Confirm---在运行命令前提示确认信息
二、PowerCLI
1. 通常,vSphere PowerCLI Cmdlets在完成命令任务之后返回结果。若希望执行命令后立刻返回而不等任务完成,可以用'RunAsync' parameter。
简单的PowerCLI例子:
Remove-VM -VM "Windows 2008" == Get-VM -Name "Windows 2008" | Remove-VM
注:PowerCLI中不支持将字符串传递给管道。
PowerCLI可能不会正确处理非字母的账户,防止这个问题可以用单引号''将非字母部分引起来。
eg, 用PowerCLI管理和控制vSphere,则需要连接到一个ESX/ESXi实例或vCenter Server上(user/pwd=Adminis!ra!or/pa$$word):
Connect-VIServer -Server 10.23.112.235 -Protocol https -Username 'Adminis!ra!or' -Password 'pa$$word'
2. 有两种办法可以通过PowerCLI使用ESXiCLI
(1) 通过Get-ESXiCLI cmdlet;
(2) 通过.NET方法
3. 管理vSphere上VM的常用Commands
a. View all VMs on target system.
Get-VM
b. Save the name and power state properties of VMs in the ResourcePool1 resource pool into a file named myVMProperties.txt
$respool = Get-ResourcePool ResourcePool1
Get-VM-Location $respool | Select-Object Name, PowerState > myVMProperties.txt
c. Start the VM1.
Get-VM VM1 | Start-VM
d. Get info of the GOS of the VM1
Get-VMGuest VM1 | fc
e. Shut down the OS of the VM1
Shutdown-VMGuest VM1
f. Power off the VM1
Stop-VM VM1
g. Move the VM1 from the Host01 host to Host02 host
Get-VM -Name VM1 -Location Host01 | Move-VM -Destination Host02
4. Add a Standalone Host to a vCenter Server System with 'Add-VMHost'
a. View all hosts on the vCenter Server that you have established a connection with.
Get-VMHost
b. Add the Host01 standalone host
Add-Host -Name Host01 -Location (Get-Datacenter DC) -User root -Password pass
5. Activate Maintenance Mode for a Host on vCenter Server
a. Save the Host01 object as a variable
$vmhost = Get-VMHost -Name Host01
b. Get the cluster to which Host01 belongs and save the cluter object as a variable
$varhostCluster = Get-Cluter -VMHost $vmhost
c. Create a new datacenter named DC
New-Datacenter -Location $folder -Name DC

浙公网安备 33010602011771号