如何用VMware PowerShell脚本来收集vCenter库存数据

413 阅读4分钟

在管理VMware vCenter环境时,库存报告是一个常见的请求。了解这个VMware PowerShell脚本如何使这种请求快速而简单。

shutterstock-590267255.jpg

图片:Shutterstock/SidorArt

作为一个管理VMware虚拟环境并经历过几次公司合并的人,运行库存审计对我来说是第二天性。为了更好地管理环境,保持你的虚拟机的最新库存总是一个好主意,但由于技术的不断变化,系统以正常的速度建立或退役,它可能像试图击中一个移动的目标。

像往常一样,脚本是这里的关键。这个基于VMware的PowerShell脚本可以帮助你快速而轻松地收集库存数据。我的同事Brad Doran,亚马逊网络服务的高级技术客户经理,为我提供了这个脚本,我在这里使用它是经过他的许可的。例如,你可以把它复制并粘贴到一个名为VMware_Inventory.ps1的本地文件中。

前提条件

使用Windows 10(理论上有可能在Windows 7中运行,但你可能会对过时的PowerShell版本感到头痛,因为这个脚本至少需要PowerShell 4.0)。

以管理员身份运行Windows PowerShell ISE(你也可以使用普通的PowerShell,但我发现ISE对最大的结果以及错误评估是最好的)。

在PowerShell ISE窗口中使用此注释安装VMware PowerCLI模块。

Install-Module -Name VMware.PowerCLI

如果你得到一个错误,说你需要NuGet提供者2.8.201版本,只要点击是,这个过程将为你下载和安装。这将需要一些时间,然后你需要点击Yes继续,再过一会儿,你会看到程序在安装相关的VMWare.PowerCLI包。

由于该脚本需要VMware.VimAutomation.Core模块,也要确保它是最新的版本(截至2021年10月),通过这个命令安装。

Install-Module -Name VMware.VimAutomation.Core -RequiredVersion 10.0.0.7893909

点击 "是 "继续,再过一会儿,你会看到程序在安装相关的VMWare软件包。

如果你收到一个错误说明。"PackageManagement\Install-Package : 新模块'VMware.VimAutomation.Core'的认证码'CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US' 。版本为'10.0.0.7893909'的新模块'VimAutomation.Core'与之前安装的版本为'12.4.0.18627056'的模块'CN=DigiCert Trusted Root G4, OU=www.digicert.com, O=DigiCert Inc, C=US'的认证码发行方不匹配。如果你仍然想安装或更新,使用SkipPublisherCheck参数"

运行此命令。

Install-Module -Name VMware.VimAutomation.Core -RequiredVersion 10.0.0.7893909 -SkipPublisherCheck

你也可以到这里下载最新版本到("C:\Program Files (x86)\VMWare\Infrastructure\PowerCLI\Modules")。

www.powershellgallery.com/packages/VM…

定制脚本

该脚本依赖于这些变量(图A)

vcs = @("vCenterFQDN") # 你的vCenter服务器的FQDN。 logFile = "C:\Temp\VMInventory.csv" # 你想保存CSV文件的地方
vcsCluster = "\*" # 过滤你想从哪个集群提取虚拟机统计数据 businessUnitName = "Element" # 脚本收集统计数据的业务单元名称

1.jpg

图A

对于$vcs,你可以将@("vCenterFQDN")替换为带引号的vCenter服务器的名称;否则脚本会提示你输入该名称。

对于$logFile,可以相应地改变日志文件的路径和名称。

对于 $vcsCluster,你可以指定要收集数据的集群,或者让这一行保持原样,以便从所有集群获取信息。

对于 $businessUnitName,用你的业务单位、部门或组来替换例子中的 "元素 "条目。

查看: 检查表,服务器清单 (TechRepublic Premium)

运行脚本

点击 "文件",然后 "打开",浏览你保存脚本文件的地方,选择它,然后把它加载到PowerShell ISE。点击绿色按钮来执行它。

如果你得到一个与安全策略有关的错误,或者脚本没有签名,请运行这个命令来允许本地脚本和远程签名的脚本。

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

如果你让$vcs变量保持不变,你将被提示输入vCenter服务器名称(图B)

2.jpg

图B

一旦你输入了名称,就会提示你对vCenterj进行认证(图C)。请确保使用一个具有管理员级别凭证的账户

3.jpg

图C

然后你会看到脚本正在运行,并积极收集数据(图D)

4.jpg

图D

脚本将显示结果,如果你把相关的变量留在原处,还可以把细节保存到 "C:\Temp\VMInventory.csv"(图E

5.jpg

图E

(注意我已经删除了列出的FQDN条目,因为这是在一个活跃的商业环境下运行的。)

谢谢你,Brad,每个VMware管理员都应该在他们的工具箱中拥有一个优秀的工具

如果你在运行这个脚本时有任何问题,请通过下面的电子邮件链接与我联系(在 "完整简历|查看Scott的所有内容 "的左边)。

#Requires -Version 4
#Requires -Modules VMware.VimAutomation.Core
 
<#
    .SYNOPSIS
 
    Create an inventory in CSV format of virtual machines in vCenter.
 
    .DESCRIPTION
 
    This script is meant to perform an inventory of Virtual Machines. It can connect to multiple vCenters to pull
    statistics from and it can pull statistics from multiple Host Clusters. This script performs read-only operations.
    Output is formatted as CSV using a standard layout.
 
    Variable Details
    $vcs - An array containing the list of vCenter servers to connect to.
    $logFile - The location of where to save the output in CSV format.
    $vcsCluster - The name of the cluster. It accepts wildcard characters, but it cannot be empty.
    $businessUnitName - the busines unit, group or department which owns/supports this environment
 
    Credential Requirements
    $vcsCreds - A user credential that has access to login to vCenter with Read-Only rights at a minimum.
    $wmiCreds - A user credential that has access to perform WMI queries locally on the Windows Virtual Machines
 
 
#>
 
Clear-Host
 
# Edit these variables for your specific environment
$vcs = @("vCenterFQDN")                 # FQDN of your vCenter server.
$logFile = "C:\Temp\VMInventory.csv"    # Where you want to save the CSV file
$vcsCluster = "*"                       # Filters which cluster you want to pull VM stats from.
$businessUnitName = "Element"     # Name of Business Unit that the script is gathering stats for
 
if($vcs -contains "vCenterFQDN"){
    $vcs = Read-Host -Prompt "FQDN of vCenter Server"
}
$vcsCreds = Get-Credential -Message "vCenter Credentials"
#$wmiCreds = Get-Credential -Message "WMI Credentials"
 
Import-Module VMware.VimAutomation.Core
Connect-VIServer $vcs -Credential $vcsCreds | Out-Null
 
$vms = Get-Cluster -Name $vcsCluster | Get-VM
$count = 0
$results = @()
$Script:ProgressPreferenceOriginal = $ProgressPreference
Clear-Host
foreach($vm in $vms){
    # Progress Bar setup
    $count++
    $percentComplete = [math]::Round(($count / $vms.Count) * 100,1)
    Write-Progress -Activity "Collecting info on $($vm.Name)" -Status "$percentComplete% Complete" -PercentComplete $percentComplete
 
    # Store VM stat info in PSObject
    $object = New-Object PSObject
    Add-Member -InputObject $object -MemberType NoteProperty -Name BusinessUnit -Value $businessUnitName
    Add-Member -InputObject $object -MemberType NoteProperty -Name Name -Value $vm.Name
    Add-Member -InputObject $object -MemberType NoteProperty -Name Domain -Value (($vm.Guest.Hostname.Split('.') | Select-Object -Skip 1) -join '.')
    Add-Member -InputObject $object -MemberType NoteProperty -Name Location -Value " "
    Add-Member -InputObject $object -MemberType NoteProperty -Name IPAddress -Value ($vm.Guest.IPAddress -join ", ")
    Add-Member -InputObject $object -MemberType NoteProperty -Name Function -Value " "
    Add-Member -InputObject $object -MemberType NoteProperty -Name PorV -Value "Virtual"
    Add-Member -InputObject $object -MemberType NoteProperty -Name vCluster -Value ($vm | Get-Cluster).Name
    Add-Member -InputObject $object -MemberType NoteProperty -Name vHost -Value $vm.VMHost
    Add-Member -InputObject $object -MemberType NoteProperty -Name Make -Value "N/A"
    Add-Member -InputObject $object -MemberType NoteProperty -Name Model -Value "N/A"
    Add-Member -InputObject $object -MemberType NoteProperty -Name SerialNumber -Value "N/A"
    Add-Member -InputObject $object -MemberType NoteProperty -Name CPU -Value $vm.NumCpu
    Add-Member -InputObject $object -MemberType NoteProperty -Name vSocket -Value ($vm.NumCpu / $vm.CoresPerSocket)
    Add-Member -InputObject $object -MemberType NoteProperty -Name CoreCount -Value $vm.CoresPerSocket
    Add-Member -InputObject $object -MemberType NoteProperty -Name MemoryGB -Value $vm.MemoryGB
    Add-Member -InputObject $object -MemberType NoteProperty -Name OperatingSystem -Value $vm.Guest.OSFullName
    Add-Member -InputObject $object -MemberType NoteProperty -Name UsedSpaceGB -Value ([math]::Round($vm.UsedSpaceGB, 0))
    Add-Member -InputObject $object -MemberType NoteProperty -Name ProvisionedSpaceGB -Value ([math]::Round($vm.ProvisionedSpaceGB,0))
    Add-Member -InputObject $object -MemberType NoteProperty -Name Environment -Value " "
    # Stores the PSObject containing VM stats in to an PSObject array
    $results += $object
}
 
# The Sort-Object is specifically set up so that the Export-Csv and Out-GridView do not truncate the properties of the individual PSObjects in
# the array.
$results | Out-GridView
$results | Export-Csv -Path $logFile -NoTypeInformation
Write-Host "Output saved to $logFile"
 
Disconnect-VIServer -Server * -Confirm:$false -Force | Out-Null

还可以看到