VIProperties

The New-VIProperty cmdlet, that was introduced with PowerCLI 4.1, offers endless possibilities to add new properties to any PowerCLI object.

For an overview of what you can do with the New-VIProperty cmdlet have a look at my PowerCLI 4.1 brings the New-VIProperty cmdlet post.

I created this page to collect useful code blocks and extension properties that can be used with the new cmdlet.

Since August 17th 2011 all the New-VIProperty entries from this page are now also available as a module. For the installation instructions see the VIProperties in a Module post.

VIProperty 140625
VIProperty 140625
VIProperty_140625.zip
3.3 KiB
Details...

Feel free to forward me your New-VIProperty statements and I will include them in the list.


Cluster

NumberOfHosts

New-VIProperty -Name NumberOfHosts -ObjectType Cluster `
	-Value {
		param($cluster)

		@($cluster.Extensiondata.Host).Count
	} `
	-BasedOnExtensionProperty 'Host' `
	-Force

NumberOfVMs

New-VIProperty -Name NumberOfVMs -ObjectType Cluster `
	-Value {
		param($cluster)

		($cluster.Extensiondata.Host | %{Get-View $_} | `
		Measure-Object -InputObject {$_.Vm.Count} -Sum).Sum
	} `
	-BasedONextensionProperty 'Host' `
	-Force

NumberVmotions

Credit: Maish Saidel-Keesing

New-VIProperty -Name NumberVmotions -ObjectType Cluster -Value {
	param($cluster)

	$cluster.ExtensionData.Summary.NumVmotions
} -Force

NumCPU

Credit: Alan Renouf

New-VIProperty -Name NumCPU -ObjectType Cluster `
   -Value {
      $TotalPCPU = 0

      $Args[0] | Get-VMHost | foreach {
         $TotalPCPU += $_.NumCPU
      }
   $TotalPCPU
} -Force

NumPoweredOnvCPUs

Credit: Alan Renouf

New-VIProperty -ObjectType Cluster -name NumPoweredOnvCPUs `
	-Value {
		$TotalvCPU = 0
		$Args[0] | Get-VMHost | foreach {
			$TotalvCPU += $_.NumPoweredOnvCPUs
		}
		$TotalvCPU
 } -Force

NumvCPUs

Credit: Alan Renouf

New-VIProperty -Name NumvCPUs -ObjectType Cluster `
	-Value {
		$TotalvCPU = 0
		$Args[0] | Get-VMHost | foreach {
			$TotalvCPU += $_.NumvCPUs
		}
		$TotalvCPU
 } -Force

Datastore

CapacityGB

New-VIProperty -Name CapacityGB -ObjectType Datastore `
	-Value {
		param($ds)

		[Math]::Round($ds.CapacityMB/1KB,1)
	} `
	-Force

FreeGB

New-VIProperty -Name FreeGB -ObjectType Datastore `
	-Value {
		param($ds)

		[Math]::Round($ds.FreeSpaceMb/1KB,1)
	} `
	-Force

NumberOfVMs

Credit: Robert van den Nieuwendijk

New-VIProperty -Name NumberOfVMs -ObjectType Datastore `
	-Value {
		param($ds)

		$ds.ExtensionData.VM.Length
	} `
	-Force

PercentFree

Credit: Sean Duffy

New-VIProperty -Name PercentFree -ObjectType Datastore -Value {
	param($ds)

	"{0:P2}" -f ($ds.FreeSpaceMB/$ds.CapacityMB)
} -Force

ProvisionedGB

New-VIProperty -Name ProvisionedGB -ObjectType Datastore `
	-Value {
		param($ds)

		[Math]::Round(($ds.ExtensionData.Summary.Capacity - $ds.ExtensionData.Summary.FreeSpace + $ds.ExtensionData.Summary.Uncommitted)/1GB,1)
	} `
	-BasedONextensionProperty 'Summary' `
	-Force

Harddisk

Datastore

New-VIProperty -Name Datastore -ObjectType Harddisk -Value {
	param($hd)

	$hd.Filename.Split(']')[0].TrimStart('[')
} -Force

UnitNumber

New-VIProperty -Name UnitNumber -ObjectType Harddisk `
	-ValueFromExtensionProperty 'UnitNumber' -Force

PhysicalNic

LinkState

New-VIProperty -Name LinkState -ObjectType PhysicalNic -Value {
	param($nic)

	if($nic.Extensiondata.LinkSpeed){"up"}else{"down"}
} -Force

Portgroup

vCenterServer

New-VIProperty -Name vCenterServer `
	-ObjectType DistributedPortgroup,VirtualPortgroup `
	-Value {
		$Args[0].Uid.Split(':')[0].Split('@')[1]
	} -Force

ScsiController

Harddisk

New-VIProperty -Name Harddisk -ObjectType ScsiController -Value {
	param($sc)

	foreach($device in $sc.ExtensionData.Device){
		($sc.Parent.ExtensionData.Config.Hardware.Device | `
		where {$_.Key -eq $device}).DeviceInfo.Label
	}
} -Force

ScsiLun

lunDatastoreName

New-VIProperty -Name lunDatastoreName -ObjectType ScsiLun -Value {
  param($lun)

  $ds = $lun.VMHost.ExtensionData.Datastore | %{Get-View $_} |
    where {$_.Summary.Type -eq "VMFS" -and
      ($_.Info.Vmfs.Extent | where {$_.DiskName -eq $lun.CanonicalName})}
    if($ds){
      $ds.Name
    }
} -Force

lunID

New-VIProperty -Name lunID -ObjectType ScsiLun -Value {
	param($lun)

	[int](Select-String ":L(?<lunID>\d+)$" `
		-InputObject $lun.RuntimeName).Matches[0].Groups['lunID'].Value
} -Force

Snapshot

Datacenter

Credit: Alan Renouf

New-VIProperty -Name "Datacenter" -ObjectType Snapshot `
 -Value {
  param ($Snapshot)
  Get-Datacenter -VM ($Snapshot.VM)
 } -Force

DaysOld

Credit: Alan Renouf

New-VIProperty -Name "DaysOld" -ObjectType Snapshot `
 -Value {
  param ($Snapshot)
  ((Get-Date) - $Snapshot.Created).Days
 } -Force

vCenter

Credit: Alan Renouf

New-VIProperty -Name "vCenter" -ObjectType Snapshot `
 -Value {
  param ($Snapshot)
  ([Uri](Get-VM $Snapshot.VM).ExtensionData.Client.ServiceUrl).Host
 } -Force

VirtualMachine

BootDelay

New-VIProperty -Name "BootDelay" -ObjectType VirtualMachine `
	-Value {
		param($vm)

		$vm.ExtensionData.Config.BootOptions.BootDelay
	}  -BasedOnExtensionProperty "Config.BootOptions" `
	-Force

BootTime

Credit: Robert van den Nieuwendijk

New-VIProperty -Name BootTime -ObjectType VirtualMachine `
  -Value {
    param($vm)
    $vm.ExtensionData.Summary.Runtime.BootTime.ToLocalTime()
  } -Force

CBTEnabled

Credit: Alan Renouf

New-VIProperty -Name CBTEnabled -ObjectType VirtualMachine `
  -ValueFromExtensionProperty "Config.ChangeTrackingEnabled" `
  -Force

CpuHotAddEnabled

Credit: Hal Rottenberg

New-VIProperty -Name 'CpuHotAddEnabled' `
	-BasedOnExtensionProperty 'Config.ExtraConfig' `
	-ObjectType VirtualMachine `
	-Value {
		param($vm)
		[bool]( $vm.ExtensionData.Config.ExtraConfig | `
			? { $_.key -eq 'vcpu.hotadd' }).Value
	} -warningAction 'silentlycontinue' -Force

DNSname

Credit: Jonathan Medd

New-VIProperty -Name DNSName -ObjectType VirtualMachine -Value {
	param($vm)

	$vm.ExtensionData.Guest.Hostname
} -BasedOnExtensionProperty "Guest.Hostname" -Force

MemoryHotAddEnabled

Credit: Hal Rottenberg

New-VIProperty -Name 'MemoryHotAddEnabled' `
	-BasedOnExtensionProperty 'Config.ExtraConfig' `
	-ObjectType VirtualMachine `
	-Value {
		param($vm)
		[bool]( $vm.ExtensionData.Config.ExtraConfig | `
			? { $_.key -eq 'mem.hotadd' }).Value
	} -WarningAction 'silentlycontinue' -Force

MemReservation

Credit: Alan Renouf

New-VIProperty -Name MemReservation -ObjectType VirtualMachine `
	-Value {
		param($vm)

		$vm.ExtensionData.Summary.Config.memoryReservation
	} -Force

NumVirtualDisks

Credit: Alan Renouf

New-VIProperty -Name NumVirtualDisks -ObjectType VirtualMachine `
	-Value {
		param($vm)

		$vm.ExtensionData.Summary.Config.numVirtualDisks
	} -Force

OSName

Credit: Jonathan Medd

New-VIProperty -Name "OSName" -ObjectType VirtualMachine -Value {
	param($vm)

	$vm.ExtensionData.Guest.GuestFullName
	} -BasedOnExtensionProperty "Guest.GuestFullName" -Force

SnapshotSpaceUsed

Ignore the warning about the ‘$_’ variable

New-VIProperty -Name SnapshotSpaceUsed -ObjectType VirtualMachine -Value {
	param($vm)

	$fileList = $vm.ExtensionData.LayoutEx.Disk | %{
		$_.Chain | Select -Skip 1 | %{
			$_.FileKey | %{
				$_
			}
		}
	}
	$vm.ExtensionData.LayoutEx.File | where{$fileList -contains $_.Key} | %{
		$snapSize += $_.Size
	}
	$snapSize
} -Force -BasedOnExtensionProperty 'LayoutEx'

ToolsVersion

Credit: Carter Shanklin

New-VIProperty -Name ToolsVersion -ObjectType VirtualMachine `
	-ValueFromExtensionProperty ‘config.tools.ToolsVersion’ `
	-Force

ToolsVersionStatus

Credit: Hal Rottenberg

New-VIProperty -Name ToolsVersionStatus -ObjectType VirtualMachine -Value {
	param($vm)
	$vm.ExtensionData.Guest.ToolsVersionStatus
} -Force

vCenterServer

Credit: Robert van den Nieuwendijk

New-VIProperty -Name vCenterServer -ObjectType VirtualMachine `
	-Value {$Args[0].Uid.Split(“:”)[0].Split(“@”)[1]} -Force

VMCluster

Credit: Stevie.R

New-VIProperty -Name VMCluster -ObjectType VirtualMachine `
  -Value {param($vm)($vm|Get-Cluster).Name} -Force

VMIenabled

New-VIProperty -Name VMIenabled -ObjectType VirtualMachine `
	-Value {
		param($vm)

		($vm.Extensiondata.Config.Hardware.Device | where {$_.GetType().Name -eq "VirtualMachineVMIROM"}) -ne $null
	} -BasedOnExtensionProperty "Config.Hardware.Device" `
	-Force

VmxDatastoreFullPath

Credit: Hal Rottenberg

New-VIProperty -Name VmxDatastoreFullPath `
	-ObjectType VirtualMachine `
	-ValueFromExtensionProperty Config.Files.VmPathName `
	-Force

WebShortcut URL

Credit API 4 part: Robert van den Nieuwendijk
API 5 part: me

New-VIProperty -Name WebShortcut -ObjectType VirtualMachine `
	-Value {
		param($vm)

		$vCenterServer = $vm.Uid.Split(“:”)[0].Split(“@”)[1]
		if($vm.ExtensionData.Client.ServiceContent.About.ApiVersion.Split('.')[0] -ge 5){
			$Uuid = $vm.ExtensionData.Client.ServiceContent.About.InstanceUuid
			$Id = $vm.Id.Replace("e-v","e:v")
			"https://${vCenterServer}:9443/vsphere-client/vmrc/vmrc.jsp?vm=${Uuid}:${id}"
		}
		else{
			$Id = $vm.Id.Replace("e-v","e|v")
			“https://$vCenterServer/ui/?wsUrl=http://localhost:80/sdk&mo=${Id}&{inventory}=none&tabs=hide_”
		}
	} -Force | Out-Null

YellowFolderName

New-VIProperty -Name 'YellowFolderName' -ObjectType 'VirtualMachine' -Value {
	param($vm)

	$entity = Get-View $vm.ExtensionData.ResourcePool
	while($entity.GetType().Name -ne 'Folder'){
		$entity = Get-View $entity.Parent
	}
	$entity.Name
} -Force -BasedOnExtensionProperty 'ResourcePool'

YellowFolderName (recursive)

Sample of a recursive function.

New-VIProperty -Name 'YellowFolderName' -ObjectType 'VirtualMachine' -Value {
	param($vm)

	function Get-FirstFolder{
		param($entityMoRef)

		$entity = Get-View $entityMoRef
		while($entity.GetType().Name -ne 'Folder'){
			$entity = Get-FirstFolder $entity.Parent
		}
		$entity
	}

	(Get-FirstFolder $vm.ExtensionData.ResourcePool).Name
} -Force -BasedOnExtensionProperty 'ResourcePool'

VMHost

AvgCPUUsage24Hr

Credit: Hal Rottenberg

New-VIProperty -ObjectType VMHost -name AvgCPUUsage24Hr `
	-Value {
		“{0:f2}” -f ($Args[0] | `
			Get-Stat -stat cpu.usage.average | `
			where { $_.Instance -eq “” } | `
			Measure-Object -Property Value -Average).Average
	} `
	-Force

ClusterName

Credit: Jonathan Medd

New-VIProperty -Name ClusterName -ObjectType VMHost `
	-Value {
		param($vmhost)
		$vmhost.Parent.Name
	} `
	-Force

Hardware

New-VIProperty -Name 'Hardware' -ObjectType 'VMHost' `
	-ValueFromExtensionProperty 'Hardware'

MemoryTotalGB

Credit: Jonathan Medd

New-VIProperty -Name MemoryTotalGB -ObjectType VMHost `
	-Value {
		param($vmhost)
		[Math]::Round($vmhost.MemoryTotalMB/1KB,1)
	} `
	-Force

Number of powered on guests

Credit: FillDeeUK

New-VIProperty -ObjectType VMHost -name NumberOfPoweredOnVMs -Value {
    ($Args[0] | Get-VM | ?{$_.PowerState -eq “PoweredOn”} | Measure-Object).Count
} -Force

NumberOfVMs

Credit: Carter Shanklin

New-VIProperty -ObjectType VMHost -name NumberOfVMs `
	-Value {($Args[0] | Get-VM | Measure-Object).Count } `
	-Force

NumPoweredOnvCPUs

Credit: Alan Renouf

New-VIProperty -ObjectType VMHost -name NumPoweredOnvCPUs `
 -Value {
   $TotalvCPU = 0
   $Args[0] | Get-VM | where { $_.PowerState -eq "PoweredOn" } | foreach {
    $TotalvCPU += $_.NumCPU
   }
   $TotalvCPU
 } -Force

NumvCPUs

Credit: Alan Renouf

New-VIProperty -ObjectType VMHost -name NumvCPUs `
 -Value {
   $TotalvCPU = 0
   $Args[0] | Get-VM | foreach {
    $TotalvCPU += $_.NumCPU
   }
   $TotalvCPU
 } -Force

16 thoughts on “VIProperties

  1. Hi Luc,

    every Time when i load the VIProperty Module i received this Error.
    Add-PSSnapin : Error: Cannot add Windows PowerShell snap-in VMware.VimAutomation.Core because it is already added. Verify the name of the snap-in and try again.
    Bei C:\Windows\system32\WindowsPowerShell\v1.0\Modules\VIProperty\VIProperty.ps
    m1:2 Zeichen:13
    + Add-PSSnapin <<<< -Name VMware.*
    + CategoryInfo : InvalidArgument: (VMware.VimAutomation.Core:Stri
    ng) [Add-PSSnapin], PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad
    dPSSnapinCommand

    Add-PSSnapin : Error: Cannot add Windows PowerShell snap-in VMware.VimAutomation.Vds because it is already added. Verify the name of the snap-in and try again.
    Bei C:\Windows\system32\WindowsPowerShell\v1.0\Modules\VIProperty\VIProperty.ps
    m1:2 Zeichen:13
    + Add-PSSnapin <<<< -Name VMware.*
    + CategoryInfo : InvalidArgument: (VMware.VimAutomation.Vds:Strin
    g) [Add-PSSnapin], PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad
    dPSSnapinCommand.

    What can i do to prevent this Error?
    Regards
    Maik

  2. the ViProperty for LunID doesn’t work because it’s missing the capture group:

    New-VIProperty -Name lunID -ObjectType ScsiLun -Value {
    param($lun)

    [int](Select-String “:L(?\d+)$” `
    -InputObject $lun.RuntimeName).Matches[0].Groups['lunID'].Value
    } -Force

  3. Hi all!
    I often stumble across incorrect/non-optimal usage of Split method. Check the reference here: http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx

    Invoking method with single parameter, eg ‘[DatastoreName]‘.Split(‘[]‘), treats the parameter as a char array, not a string. So the source string is split at every occurrence of any character in the parameter string. Thus the example above allows to extract the datastore name with single invocation.
    // Just a little remark to make your code look nifty.

  4. Hi LucD, I have installed the new module but when I run any of the above I get this error back.
    WARNING: The specified script block may contain a reference to the ‘$_’ variable. If you want to reference the object being extended, please use ‘$args[0]‘ instead.

    any help would be appreciated. Thanks RichG

    • Hi Richard, that is a warning, and shouldn’t cause any problems with loading the module.
      Can you see the VIproperties after you loaded the module ? Do a

      Get-VIProperty

      I’ll update the module in any case to avoid the warning.

  5. So I have a report showing a huge number of over-built VMs – what a surprise :). Anyway, trying to write a powershell script to downgrade the number of cores.

    Problem is set-VM only sets sockets, not cores. Not seeing much about this online except for this sample. I do not really understand what is going on within this code sample, and it seemed to cause problems with the GUI later on for the Author. Is there a better write up you can point me to on this so I know how it works instead of just blindly copying it into my script :)
    $spec=New-Object –Type VMware.Vim.VirtualMAchineConfigSpec –Property @{“NumCoresPerSocket” = 2}

    (Get-VM –Name Test_VM).ExtensionData.ReconfigVM_Task($spec)

    The problem is, the person who posted it reported they got errors whenever setting Cores/ sockets to a different value later via the GUI. Is this safe?

    Seems like this should not be too difficult – in general, I wanted to approach it like this:
    1. Set a variable = import-csv (which contains VM names and recommended new CPU/Mem settings
    2. For each VM in the CSV, discover current Socket/ Core count relationship
    – I was hoping to get to that via get-vm, but cores are not exposed there
    3. Put in an algorithm to change the new core count to the optimal ratio of cores to sockets (i.e. if the desired state was 3 cores, then set sockets down to 1 and set cores to 3).

    Thanks for any advice :)
    -Don

    • Hi Don, there is a limit on the number of cores that can be defined, and that depends on the OS you defined for the VM.
      See also Re: vSphere 5. vCPU Sockets and Cores per CPU bug (PowerCLI)

      The current number of cores per socket is available, but you will have to descend into the ExtensionData.

      Get-VM |
      Select Name,NumCPU,
      @{N="Cores#";={$_.ExtensionData.Config.Hardware.NumCoresPerSocket}}

      Let me know if this helps you in advancing with your script, otherwise feel free to ask.

  6. I am certain there is a better place to pose this question but I have not been able to find it so here goes. I created a Custom Attribute, via script, for all the VM’s in my vCenter called SRM. I have not added any VM’s yet since I did this but I am curious to know this, will new VM’s automatically pick up this attribute or will I have to manually add it to them?

    • Hi Steve, I assume you have created a custom attribute for the VirtualMachine targettype. Something like this

      New-CustomAttribute -Name TestCA -TargetType VirtualMachine -Confirm:$false

      This custom attribute will now be available on all VMs, old and new, in your vSphere environment. You can assign a value to this custom attribute. Like this

      $ca = Get-CustomAttribute -Name TestCA
      Get-VM TestVM | Set-Annotation -CustomAttribute $ca -Value "Some text"

      Watch out, if you remove a custom attribute, it will be gone for all the VMs !

  7. We also work on “Trade Lines” and it will help you to increase your debt to income ratio (DTI). We provide this for better service. This service will boost your credit score, regardless of your credit history.

  8. I am looking to baseline my CPU settings now that I have moved to esx 5 and need some help with locating where the virtual CPU setting is. numcpuPkgs works but throws an error and I can’t find the property anyplace. The other two values work. My sample commands are below.

    Any help would be appreciated.

    Thanks
    -mark

    ## create the VirtualMachineConfigSpec with which to reconfig the VM

    $vSocket = New-Object -Type VMware.Vim.VirtualMachineConfigSpec -Property @{“numcpuPkgs” = 1}
    (Get-VM _2008x64).ExtensionData.ReconfigVM_Task($vSocket)

    $CoresPerSocket = New-Object -Type VMware.Vim.VirtualMachineConfigSpec -Property @{“NumCoresPerSocket” = 2}
    (Get-VM _2008x64).ExtensionData.ReconfigVM_Task($CoresPerSocket)

    $TotalCores = New-Object -Type VMware.Vim.VirtualMachineConfigSpec -Property @{“numcpus” = 2}
    (Get-VM _2008x64).ExtensionData.ReconfigVM_Task($TotalCores)

  9. Thanks for putting this together and also to all those who contributed. It’s really cool and works.

  10. Pingback: Tweets that mention A collection of VIProperty code blocks | LucD notes -- Topsy.com

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>