这几天研究PowerCLI,积累了几个例子,记下来,以便以后或者大家使用。部分例子来着网络,具体出处参考附录
1 获取vm 磁盘 和磁盘对应的datastore的信息
这个例子可以针对一台虚机有多个磁盘,但每个磁盘可能所属datastore不同,所以需要列出来查看
Get-VM | %{ $_.HardDisks | Select @{N="VM";E={$_.Parent.Name}}, Name, @{N="DS";E={$_.Filename.Split(']')[0].TrimStart('[')}} }
如果分着取的话也可以直接转换为
$targetVM = Get-VM -Name "vmname" $disks = Get-HardDisk $targetVM $diskDatastore = $disks.Filename.Split(']')[0].TrimStart('[')
2 获取vm,cpu,memory,guest,vmdk,datastore信息,并保存为HTML文档,这里主要是HTML文档生成的语法
$a = "<title>$name</title>" $a = $a +"<style>" $a = $a + "BODY{background-color:blue;}" $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}" $a = $a + "TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:thistle}" $a = $a + "TD{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:PaleGoldenrod}" $a = $a + "</style>" foreach($cluster in Get-Cluster){ foreach($rp in Get-ResourcePool -Location $cluster){ $report = foreach($vm in (Get-VM -Location $rp)){ Get-HardDisk -VM $vm | Select @{N='Cluster';E={$cluster.Name}}, @{N='ResourcePool';E={$rp.Name}}, @{N='VM';E={$vm.Name}}, @{N='HD';E={$_.Name}}, @{N='Datastore';E={($_.Filename.Split(']')[0]).TrimStart('[')}}, @{N='Filename';E={($_.Filename.Split(' ')[1]).Split('/')[0]}}, @{N='VMDK Path';E={$_.Filename}}, @{N='Format';E={$_.StorageFormat}}, @{N='Type';E={$_.DiskType}}, @{N='CapacityGB';E={$_.CapacityGB}} } $report | ConvertTo-Html -Head $a | Out-File -FilePath "C:\temp\$($cluster.Name)-$($rp.Name)-report.html" } }
样例如下:
Cluster | ResourcePool | VM | HD | Datastore | Filename | VMDK Path | Format | Type | CapacityGB |
---|---|---|---|---|---|---|---|---|---|
Cluster2 | Resources | BPPM_Oracle | 硬盘 1 | NFS_Storage_OS_VOL3 | BPPM_Oracle | [NFS_Storage_OS_VOL3] BPPM_Oracle/BPPM_Oracle-000001.vmdk | Thin | Flat | 100 |
Cluster2 | Resources | rcwin01 | 硬盘 1 | VMRestoreVol | rcwin01 | [VMRestoreVol] rcwin01/rcwin01.vmdk | Thin | Flat | 100 |
Cluster2 | Resources | install-test | 硬盘 1 | NFS_Storage_OS_VOL3 | install-test | [NFS_Storage_OS_VOL3] install-test/install-test.vmdk | Thin | Flat | 50 |
Cluster2 | Resources | 10.200.200.188 | 硬盘 1 | NFS_Storage_OS_VOL3 | 10.200.200.188 | [NFS_Storage_OS_VOL3] 10.200.200.188/10.200.200.188.vmdk | Thin | Flat | 100 |
Cluster2 | Resources | portal-db-test | 硬盘 1 | NFS_Storage_OS_VOL3 | portal-db-test | [NFS_Storage_OS_VOL3] portal-db-test/portal-db-test.vmdk | Thin | Flat | 100 |
3 根据datastoreid 来获取datastore的名字
这个例子后面get-view -property name 用法比较重要,power-cli有很多根据id来获取name的情况,基本都可以用这个例子来解决,避免直接获取name带来的性能问题
Get-VM -Location "可选-指定datacenter" -Name "可选-指定vm" | % { @{$_.Name=$_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}} }
可以举一反三一下,比如根据aa,获取bb的信息
4 这个例子比较有趣,可以设置输出的的格式
下面的例子是通过一条命令,获取Host, Cluster and Datastore Details
具体大家可以看这位的参考Host, Cluster and Datastore Details
Is there any way to use autosize, as the long datastore names trunctes.
Try Autosize
Get-VM (Get-content c:\temp\vms.txt) | Select-Object -Property @{Name='VMName';Expression={$_.Name}},VMHost,@{Name='ClusterName';Expression={$_.VMHost.Parent}}, @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ", "}} | FT -AutoSize
Try wrapping?
Get-VM (Get-content c:\temp\vms.txt) | Select-Object -Property @{Name='VMName';Expression={$_.Name}},VMHost,@{Name='ClusterName';Expression={$_.VMHost.Parent}}, @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ", "}} | FT -Wrap
If possible, can we use sort-object with VM Names ?
Yep, just pipe to Sort-Object
Get-VM (Get-content c:\temp\vms.txt) | Select-Object -Property @{Name='VMName';Expression={$_.Name}},VMHost,@{Name='ClusterName';Expression={$_.VMHost.Parent}}, @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ", "}} | Sort VMName
Also, can we use export-csv to export the out put to excel ?
Yep, Just pipe to Export-CSV
Get-VM (Get-content c:\temp\vms.txt) | Select-Object -Property @{Name='VMName';Expression={$_.Name}},VMHost,@{Name='ClusterName';Expression={$_.VMHost.Parent}}, @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ", "}} | Export-CSV -NoTypeInformation C:\temp\VMExport.csv
5 一条命令获取Vmhost及其网络信息
To list all ESX Hosts and their Service console information
Get-VMHost | Get-VMHostNetwork | Select Hostname, ConsoleGateway, DNSAddress -ExpandProperty ConsoleNic | Select Hostname, PortGroupName, IP, SubnetMask, ConsoleGateway, DNSAddress, Devicename
获取的样例如下
HostName | PortGroupName | IP | SubnetMask | ConsoleGateway | DNS Address | DeviceName |
esx01 | SC | 192.168.2.33 | 255.255.255.0 | 192.168.2.1 | 192.168.2.20 192.168.1.20 | vswif0 |
esx01 | SC 2 | 192.168.3.43 | 255.255.255.0 | 192.168.2.1 | 192.168.2.20 192.168.1.20 | vswif1 |
esx02 | SC | 192.168.1.12 | 255.255.255.0 | 192.168.1.254 | 192.168.1.20 | vswif0 |
esx03 | SC | 192.168.2.34 | 255.255.255.0 | 192.168.2.1 | 192.168.2.20 192.168.1.20 | vswif0 |
esx03 | SC 2 | 192.168.3.44 | 255.255.255.0 | 192.168.2.1 | 192.168.2.20 192.168.1.20 | vswif1 |
To list all ESX Hosts and their VMotion Enabled Networks :
Get-VMHost | Get-VMHostNetwork | Select Hostname, VMkernelGateway -ExpandProperty VirtualNic | Where {$_.VMotionEnabled} | Select Hostname, PortGroupName, IP, SubnetMask, VMkernelGateway, Devicename
样例如下
HostName | PortGroupName | IP | SubnetMask | VMKernelGateway | DeviceName |
esx01 | VMkernel | 192.168.3.33 | 255.255.255.0 | vmk0 | |
esx02 | VMkernel | 192.168.3.34 | 255.255.255.0 | 192.168.3.1 | vmk0 |
当然标准的获取方式如下,获取了ESX的ip,和vmotionip
Get-VMHost * | Sort Name | Get-View | Select Name,@{N="Address";E={($_.Config.Network.Vnic | ? {$_.Device -eq "vmk0"}).Spec.Ip.IpAddress,($_.Config.Network.Vnic | ? {$_.Device -eq "vmk1"}).Spec.Ip.IpAddress}} ) " " | Out-file C:\SMinfo\"HostIPandvMotionIP$(Get-Date -Format 'yyyyMMdd').txt" -append
6 如何提高查询的速度
有时候,我们可以按照规定,获取这些信息,但如果数据量特别大,脚本运行时间会很长,那如何更快速的减少联表查询,加快速度呢,下面是个好例子,这个涉及到哈希索引,哥就不懂了
Receving cluster name for vms fast.
7 获取vm name 和ip地址
Get-VM | Select Name, @{N="IP Address";E={@($_.guest.IPAddress[0])}}
以上是几个分着的例子,主要都侧重某个方面,实际要做到时候,还要再组合和调试,尤其对于初次接触powershell的人比较麻烦了,下面这个例子是我实际工作中结合别人例子改造的,供参考
8 获取vmname,vmid,ESXHOST,ESXIP,cluster,datastore,下面三个脚本功能差不多,只是速度不同,供参考
################如果不考虑性能的话,下面这个脚本比较简单易懂,但速度慢#################### Connect-VIServer -server 10.200.108.66 -user [email protected] -password 密码 Get-VM | Select Name,id, ` @{N="ESXIP";E={Get-VMHost -VM $_| Select ($_.ExtensionData.Config.Network.Vnic | ? {$_.Device -eq "vmk0"}).Spec.Ip.IpAddress}},` @{N="ESXHOST";E={(Get-VMHost -VM $_).name}}, ` @{N="Cluster";E={Get-Cluster -VM $_}}, ` @{N="Datastore";E={Get-Datastore -VM $_}},` Time | Export-Csv -NoTypeInformation c:\VMInfo\"33Export67VMinfo$(Get-Date -Format 'yyyyMMdd').csv" Disconnect-VIServer -server * -force -Confirm:$false ################考虑性能,尽量使用属性的方式获取,大概比上面节省五分之二的时间############ Connect-VIServer -server 10.200.108.67 -user [email protected] -password 密码 Get-VM | Select Name,id, ` @{Name=’ESXIP’;Expression={ &{$script:esx=get-view -Id $_.vmhostid -property name,config};($script:esx.Config.Network.Vnic | where{$_.Device -eq 'vmk0'}).Spec.Ip.IpAddress }},` vmhost, ` @{Name=’Cluster’;Expression={$_.VMHost.Parent}}, ` @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ", "}},` Time | Export-Csv -NoTypeInformation c:\VMInfo\"44Export67VMinfo$(Get-Date -Format 'yyyyMMdd').csv" Disconnect-VIServer -server * -force -Confirm:$false #############添加了硬盘对应的datastore的信息,因为有些机器不同硬盘所属datastore不同########## Connect-VIServer -server 10.200.108.67 -user [email protected] -password P@ssw0rd Get-VM | Select Name,id, ` @{Name=’ESXIP’;Expression={ &{$script:esx=get-view -Id $_.vmhostid -property name,config};($script:esx.Config.Network.Vnic | where{$_.Device -eq 'vmk0'}).Spec.Ip.IpAddress }},` vmhost, ` @{Name=’Cluster’;Expression={$_.VMHost.Parent}}, ` @{N="Storage";E={(Get-HardDisk -VM $_ |Select @{N='HD';E={$_.Name}},@{N='Datastore';E={` ($_.Filename.Split(']')[0]).TrimStart('[')}}) -replace "@{HD=","" -replace "; Datastore","" -replace "}","" -replace "{","" ` }},` Time | Export-Csv -NoTypeInformation -encoding utf8 c:\VMInfo\"Export67VMinfo$(Get-Date -Format 'yyyyMMdd').csv" Disconnect-VIServer -server * -force -Confirm:$false ##################如果想限定vm的范围,可以使用csv文件限定,减少查询################# Connect-VIServer -server 10.200.108.67 -user [email protected] -password 密码 $vmname = Import-csv "C:\VMInfo\vmhosts.csv" $vmname | %{Get-VM $_.name| Select Name,id, ` @{Name=’ESXIP’;Expression={ &{$script:esx=get-view -Id $_.vmhostid -property name,config};($script:esx.Config.Network.Vnic | where{$_.Device -eq 'vmk0'}).Spec.Ip.IpAddress }},` vmhost, ` @{Name=’Cluster’;Expression={$_.VMHost.Parent}}, ` <#@{N="Storage";E={(Get-HardDisk -VM $_ |Select @{N='HD';E={$_.Name}},@{N='Datastore';E={($_.Filename.Split(']')[0]).TrimStart('[')}}) -replace "@{HD=","" ` -replace "; Datastore","" -replace "}","" -replace "{","" ` }},`#> @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ", "}},` Time }| Export-Csv -NoTypeInformation -encoding utf8 c:\VMInfo\"Export67VMinfo$(Get-Date -Format 'yyyyMMdd').csv" Disconnect-VIServer -server * -force -Confirm:$false ###########升级版,添加了过滤条件和ip的分隔符######### Connect-VIServer -server 10.200.108.67 -user [email protected] -password P@ssw0rd Get-VM |where{$_.PowerState -eq “PoweredOn”}| Select NAME, @{Name=’VMIP’;Expression={($_.Guest.IPAddress) -join ";"}},ID,` @{Name=’VMUUID’;Expression={$_.ExtensionData.config.uuid}}, ` @{Name=’ESXIP’;Expression={ &{$script:esx=get-view -Id $_.vmhostid -property name,config};($script:esx.Config.Network.Vnic | where{$_.Device -eq 'vmk0'}).Spec.Ip.IpAddress }},` vmhost, ` @{Name=’Cluster’;Expression={$_.VMHost.Parent}}, ` @{"Name"="Datastore"; expression={($_.DatastoreIDList | %{(Get-View -Property Name -Id $_).Name}) -join ";"}} | Export-Csv -NoTypeInformation -encoding utf8 c:\VMInfo\"Export67VMinfo$(Get-Date -Format 'yyyyMMdd').csv" Disconnect-VIServer -server * -force -Confirm:$false
csv文件样例如下:
Name | Id | ESXIP | VMHost | Cluster | Storage | Time |
install-test | VirtualMachine-vm-868 | esx.vsphere.com.1 | 10.200.236.15 | Cluster2 | 硬盘 1=NFS_Storage_OS_VOL3 | |
clm-db-3 | VirtualMachine-vm-735 | esx.vsphere.com.2 | 10.200.236.16 | Cluster2 | 硬盘 1=NFS_Storage_OS_VOL3 硬盘 2=NFS_Storage_OS_VOL3 | |
test-225.4 | VirtualMachine-vm-720 | esx.vsphere.com.3 | 10.200.236.17 | Cluster2 | 硬盘 1=NFS_Storage_OS_VOL3 | |
cloudexpress | VirtualMachine-vm-1887 | esx.vsphere.com.4 | 10.200.236.18 | Cluster2 | 硬盘 1=NFS_Storage_OS_VOL3 硬盘 2=NFS_Storage_OS_VOL3 |
9 获取ESX IP 的两种方法,一定要注意以下格式,当你通过get-vm获取其他属性信息时,下面的格式可供参考
#方法一比较慢 Get-VM | Select @{N="ESXip慢";E={((Get-VMHost -VM $_).ExtensionData.Config.Network.Vnic | ? {$_.Device -eq "vmk0"}).Spec.Ip.IpAddress}} #方法二比较快 Get-VM | Select @{Name=’ESXIP’;Expression={ &{$script:esx=get-view -Id $_.vmhostid -property name,config};($script:esx.Config.Network.Vnic | where{$_.Device -eq 'vmk0'}).Spec.Ip.IpAddress }}
10 如果想看语句执行到底耗时多久,进行统计等,可以使用如下命令
#统计耗时示例 vSphere PowerCLI> Measure-Command {get-vm} Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 14 Ticks : 10142444 TotalDays : 1.17389398148148E-05 TotalHours : 0.000281734555555556 TotalMinutes : 0.0169040733333333 TotalSeconds : 1.0142444 TotalMilliseconds : 1014.2444 #统计耗时示例一 vSphere PowerCLI> (Measure-Command {get-vm}).totalseconds 0.6503594 #统计执行耗时示例二 measure-command {foreach ($vm in $vms){ $vm | select name, @{n=’CLname’;e={$HostToClusterHash[$vmsToHostHash[$($vm.name)]]}} } } #统计vm总数量 vSphere PowerCLI> (get-vm).count 78
参考:
find datastore from HardDisk
Power-Cli shows resource pools including VM,s CPU, Memory, Guest, DS, VMDK files in one HTML report
Powershell Get VM Datastore Location PowerCLI
Host, Cluster and Datastore Details
Receving cluster name for vms fast
powercli one liner to get vms clusters esx hosts and datastores这个我参考最多了