Powershell‎ > ‎

VMWare CLI


Project Onyx

Very cool tool to find the PowerCLI Code you need 

List of Performance Counters


list of commands related to stats
Get-Command -Module "VMware.VimAutomation.Core" *stat*


Get a list of stats available for a vm or host
Get-StatType -Entity servername 
Get-StatInterval
Get-StatType -Entity servername -Interval "Past Day"

Get-vm servername | Get-Stat -Stat mem.active.average -Start (Get-Date).AddHours(-2)-IntervalMins 5

Peak memory usage over past 24 hours in gb
(Get-vm servername | Get-Stat -Stat mem.active.average -Start (Get-Date).AddHours(-24) | Measure-Object -Property Value -Maximum).Maximum * 1kb / 1gb

If you change the interval units you can get older data
Get-vm servername | Get-Stat -Stat mem.usage.average -Start (Get-Date).AddHours(-168) -IntervalMins 60 | sort timestamp | select -First 5
„


Table 12-5. Default Sampling Periods and Retention
 Sampling Period Retention Period ESX, ESXi  vCenter Server
20 seconds1 day „   
5 minutes24 hours „  
1 hour7 days   
6 hour30 days  
24 hour365 days  



CPU Ready
$vms= get-vm -Location NewYork
#% CPU Ready = (CPU Ready / stat interval in milliseconds ) * 100
#( 30 min x 60 seconds * 1000 = 1800000 milliseconds ) * 100 to get percent, so we use 18000 as our divisor
$VMCPUReady = Get-Stat -Entity (get-vm $vms ) -Stat cpu.ready.summation -start (get-date).adddays(-7) -finish (get-date) -interval 30 -instance "" -ea silentlycontinue | group entity | 
   select Name, @{Name="CPU Ready Avg"; Expression= {[Math]::Round($($_.group | measure -property value -average).average,0)}},
   @{Name="% CPU Ready"; Expression= {[Math]::Round(($($_.group | measure -property value -average).average) / 18000 ,2)}}
($VMCPUReady | measure -Sum -Property "CPU Ready Avg").sum
$VMCPUReady

PowerCLI property for vSphere client GUI Cluster "Current Failover Capacity"
This seems to be the right property $cluster.ExtensionData.Summary.CurrentFailoverLevel
Get-Cluster | select name, @{Name="Current Failover Capacity"; Expression={$_.ExtensionData.Summary.CurrentFailoverLevel}} | ft -auto
„

 

Add-PSSnapin VMware.VimAutomation.Core

Get-Command -Module "VMware.VimAutomation.Core"



$cred = Get-Credential


Connect-VIServer -Server servername -Credential $cred


$VMs = Get-VM 
$VMs | measure


$Tiers = Import-Csv C:\scripts\PowerShell\VMWare\VMTiers.csv 
$Tiers | select name, tier


foreach ($server in $tiers) 
{
     Get-VM $server.name | Set-Annotation -CustomAttribute "Tier" -Value $server.tier
}





$vmhosts = Get-VMHost | Get-View
$vmhosts = get-view (Get-VMHost)
$VMHosts | select name, @{Name="Vendor";Expression={$_.summary.hardware.vendor}}, @{Name="Model";Expression={$_.summary.hardware.Model}}




$Snapshots = Get-Snapshot -VM * 
$Snapshots | select VM, Name, Description, SizeMB, Created

Email a list of VM Snapshots

Look into issue with scheduled tasks not running evidently this was fixed in PowerCLI 4 Update 1

http://communities.vmware.com/thread/240979

IF (Get-PSSnapin | where {$_.name -eq "VMware.VimAutomation.Core"}) 
    {write-host "VMware.VimAutomation.Core snapin already loaded"}
Else
    {add-PSSnapin  VMware.VimAutomation.Core}
Function check-even ($num) {[bool]!($num%2)}
$smtpServer = "mail.blah.com"
$To = "Kevin Curran <kcurran@blah.com>"
$From = "AD Reporting <ADReporting@blah.com>"

#Scheduled Task fails because connect-viserver does not use the credentials of the user running the task for some reason
#Connect-VIServer -Server servername
#http://www.powershellcommunity.org/Forums/tabid/54/aft/4295/Default.aspx
$creds = Get-VICredentialStoreItem -file "C:\Scripts\VMWare\CredFile.xml" 
Connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password 

$Snapshots = Get-Snapshot -VM * 
#$Snapshots | select VM, Name, Description, SizeMB, Created

$PreMessage = @" 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
<style>
    BODY{background-color:white;}
    TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
    TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:MidnightBlue; color:Yellow}
    TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:PaleGoldenrod}
    TR.D0 TD {background-color: White; color: black;}
TR.D1 TD {background-color: LawnGreen; color: black;}
</style>
</head><body>

“@

$PostMessage += "This script was run by " + $env:username + " on " + $env:COMPUTERNAME
$PostMessage += "<br>ScriptName: $($MyInvocation.MyCommand) "
$PostMessage += "<br>Script path: $(Split-Path -Parent $MyInvocation.MyCommand.Path)"
$PostMessage += "</body></html>"

$Message= $Snapshots | sort -Property VM | ConvertTo-Html -Property VM, Name, Description, SizeMB, Created -PreContent `
    "Please review the list and remove any unnecessary snapshots, VMWare recommends snapshots not to exceed 2 GB. <H2>Updated list of VM Snapshots </H2>" | ForEach-Object {$_}

$ModifiedHTML=ForEach ($line in $Message)
{
    $counter++
    if (check-even $counter)
     {$line.replace('<tr><td>','<tr class="d0"><td>')}
    Else
     {$line.replace('<tr><td>','<tr class="d1"><td>')}
}

$html = $PreMessage + $($ModifiedHTML | out-string) + $PostMessage

Send-MailMessage -From $From -To $To -SmtpServer $smtpServer `
-Subject "Snapshot Cleanup Time" -BodyasHTML $HTML


Guest NICs disconnected after upgrade    

$foo=Get-NetworkAdapter -VM server
$foo.ConnectionState.StartConnected
$foo.ConnectionState.Connected


Get VM ToolsVersion


IF (Get-PSSnapin | where {$_.name -eq "VMware.VimAutomation.Core"}) 
    {write-host "VMware.VimAutomation.Core snapin already loaded"}
Else
    {
        write-host "Loading VMware.VimAutomation.Core snapin"
        add-PSSnapin  VMware.VimAutomation.Core
        write-host "VMware.VimAutomation.Core snapin Loaded"
    }

$smtpServer = "mail.blah.com"
$To = "Kevin Curran <kcurran@blah.com>"
$From = "AD Reporting <ADReporting@blah.com>"
$Attachement = "C:\Scripts\VMWare\VMTools.csv"

#Scheduled Task fails because connect-viserver does not use the credentials of the user running the task for some reason
#Connect-VIServer -Server servername
#http://www.powershellcommunity.org/Forums/tabid/54/aft/4295/Default.aspx
#$creds = Get-VICredentialStoreItem -file "C:\Scripts\VMWare\CredFile.xml" 
#Connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password 
#Issue fixed in PowerCLI Version 4.1.1
Connect-VIServer -Server servername

#http://jdhitsolutions.com/blog/2010/04/powercli-get-vmtoolsversion/
Function Get-VMToolsVersion 
{
[cmdletbinding()]            
Param (
     [Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True,
     HelpMessage="You must specify a virtual machine object")]
     [VMWare.VimAutomation.Client20.VirtualMachineImpl[]]$vm
    )            

Begin {
    Write-Verbose "Starting function"
}            

Process {
    Write-Verbose "Getting view for $($vm.name)"
    $view=Get-View -viObject $vm            

    $ToolsVersion=$view.Config.Tools.ToolsVersion
    write-verbose "Found tools version value of $ToolsVersion"
    $vm | Add-Member -MemberType NoteProperty -Name "ToolsVersion" `
-Value $toolsVersion -passthru            

}            

End {
    Write-Verbose "Ending function"
}            

}

$VMTools = get-vm | get-vmtoolsversion
$VMTools | select Name, ToolsVersion, PowerState, Host, Description, Notes, NumCpu, MemoryMB | Export-Csv -NoTypeInformation $Attachement
$HTML= $VMTools | Group-Object -Property ToolsVersion | select Count, Name | ConvertTo-Html | Out-String

Send-MailMessage -From $From -To $To -SmtpServer $smtpServer `
-Subject "VM Tools Versions" -BodyasHTML $HTML -Attachments $Attachement

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah


Check for lockdown mode


get-vmhost | select Name,@{N="LockDown";E={$_.Extensiondata.Config.adminDisabled}} | ft -auto Name, LockDown



$VMHost = Get-VMHost esx10.blah.com
$VMHostView = $VMHost | Get-View

If ($VMHost.ExtensionData.Config.AdminDisabled -eq $true) {$VMHostView.ExitLockdownMode()}

$VMHostView.EnterLockdownMode()



Get-Cluster | Select Name, @{N="Host Monitoring Status";E={$_.Extensiondata.Configuration.DasConfig.HostMonitoring}}



List count of VMs per Datastore

$VMs = Get-VM | Select Name, @{N="Folder";E={$_.Folder.Name}}, @{N="DatastoreIdList";E={$_.DatastoreIdList}}
$vms | Group-Object -Property DatastoreIdList | select Count, @{N="Datastores";E={[string]::Join(',',(Get-Datastore -Id $_.Name.split(" ")| Select -ExpandProperty Name))}}



List count of VMs esx host and datastore

Get-VM servers* | select name, vmhost, @{N="Datastore";E={get-datastore -id $_.DatastoreIdList}}
Get-VM servers* | select name, vmhost, @{N="Datastore";E={[string]::join(",",(get-datastore -id $_.DatastoreIdList | select -ExpandProperty name))}}

List vm name and IP address
Get-VM server | Select name,@{N=”IP Address”;E={@($_.guest.IPAddress[0])}}