Pages

7/10/2013

Powershell: VMware guest inventory

Powershell: VMware Guest Inventory

Gather information from vCenter server about VM's. In this case I was looking for machines that were connected to more than one network or datastore.

$vcs = Read-Host "vCenter"
$user = Read-Host "userid"
$pw = Read-Host "Password for $user" -AsSecureString
#convert $pw to plain text
    $pass = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
        [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

#$vcon = Disconnect-VIServer * -Confirm:$False
$vcon = connect-viserver -Server $vcs -User $user -Password $pass

$pass = " "
$outfile = ".\"+$vcs+"-info.csv"

$reportedvms=New-Object System.Collections.ArrayList
$vms=get-view -viewtype virtualmachine | Sort-Object -Property {$_.Config.Hardware.Device | where {$_ -is [VMware.Vim.VirtualEthernetCard]} | Measure-Object | select -ExpandProperty Count} -Descending
 
foreach($vm in $vms){
$status = $vm.name
"    $status"
    $reportedvm = New-Object PSObject
    $ipnum = ($vm.guest.net | select IPaddress).IPaddress| out-string
    $path = $vm.name
    $current = get-view $vm.parent
      do {
        $parent = $current
         if($parent.Name -ne "Datastore*"){$path =  $parent.Name + "\" + $path}
         $current = Get-View $current.Parent
      } while ($current.Parent -ne $null)
    
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Path -value $path
#    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Guest -value $vm.Name
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Networks -value $($vm.network.count)
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Network -value $((get-view $vm.network).name)
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name IP -value $ipnum
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Datastores -value $($vm.datastore.count)
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Datastore -value $((get-view $vm.datastore).name)
    $networkcards =$vm.guest.net
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Nics -value $($networkcards.count)
    Add-Member -Inputobject $reportedvm -MemberType noteProperty -name Disks -value $($vm.guest.disk.count)    
    
  $reportedvms.add($reportedvm) |Out-Null
}
 
$reportedvms|Export-Csv $outfile

Disconnect-VIServer * -Confirm:$False

No comments: