## =====================================================================
## Title : GetVI-HostList
## Description : Retrieve VMware Hosts
## Author : Idera
## Date : 9/11/2008
## Input : -VIserver : Virtual Infrastructure server
## -verbose -debug
## Output : VMs
## Usage : PS> .\GetVI-HostList -VIserver myVIserver -verbose -debug
## Notes :
## Tag : PowerShell, VMware
## Change log :
## 4/1/2009 - Added input parameters and trap
## 4/1/2009 - Added Read-Host input prompts and Write-Verbose and Write-Debug statements
## =====================================================================
param
(
[string]$VIserver = "$(Read-Host 'VI Server' [e.g. vs01])",
[switch]$verbose = $true,
[switch]$debug = $false
)
function main()
{
if ($verbose) {$VerbosePreference = "Continue"}
if ($debug) {$DebugPreference = "Continue"}
Write-Verbose "Retrieve VMware Hosts..."
CheckVIToolKit
GetVI-HostList $VIserver
}
function GetVI-HostList($VIserver)
{
trap [Exception]
{
write-error $("TRAPPED: " + $_.Exception.Message);
continue;
}
# Clear Screen
Clear-Host
# Warn user they must be logged on with an account that has connection rights to the VI server.
$answer = Read-Host "`n`n`n`tNOTE: You must be logged on with an account that has connection rights to the VI server. `n`n`n`n`tPress <X> to exit, <C> to continue if you have a connection to a VI Server already or <Enter> to continue. "
if($answer -eq "x")
{
break
}
else
{
if($VIserver -eq "")
{
Write-Host "`n`n`n`tERROR- A VI server must be specified!`n`n" -foregroundcolor red
Read-Host "`n`t Press <Enter> to continue "
break
}
else
{
if($answer -eq "C")
{
# do nothing as we have a connection we can use already
}
else
{
Connect-VIServer $VIserver
Write-Host "`n`n`t You have connected to Server: $VIserver.Name with a SessionID of: $VIserver.SessionID ."
Read-Host "`n`t Press <Enter> to continue "
}
}
Clear-Host
# Display the list of Hosts found on the network.
Get-VMHost
Read-Host "`n`n`t Press <Enter> to continue "
}
} # EOF: GetVI-HostList()
function CheckVIToolKit()
{
# Before we do anything we must check to see if the user has the VI toolkit installed.
# If user does not then we prompt the user and exit.
$Error.Clear()
Get-PSSnapin vmware*
if($Error.Count -ne 0)
{
Clear-Host
Write-Host "`n`n`t`t ERROR - To run this script, the VI Toolkit must be installed and registered with Powershell. If the VI Tollkit is installed," -foregroundcolor red -backgroundColor yellow
Write-Host "`t`t go to the Settings menu in Powershell Plus and click on Manage Snapins." -foregroundcolor red -backgroundColor yellow
Read-Host "`n`n`t Press <Enter> to continue."
Clear-Host
break
}
}# EOF: CheckVIToolKit()
main
这个脚本检索VMWare主机,首先看到执行时会执行第81行的CheckVIToolKit,该方法是检索是否安装模拟,使用的一个新Cmdlets是第86行的Get-PSSnapin。
Get-PSSnapin cmdlet 获取 Windows PowerShell 管理单元,这些单元已添加到当前会话中或已在系统上注册它们。 按照检测到的顺序列出这些管理单元。
Get-PSSnapin仅获取已注册的管理单元。
这里主要检测是否安装Vmware模块。(如果没安装可以使用命令
Install-Module VMWare.PowerCLI
来安装)。
第67和76行的Cmdlet都是需要安装VMware的PowerShell模块后才会有的命令。