Creating calculated properties
You can use the Select-Object
cmdlet to select certain properties of the objects that you want to return. For example, you can use the following code to return the name and the used space, in GB, of your virtual machines:
PowerCLI C:\> Get-VM | Select-Object -Property Name,UsedSpaceGB
But what if you want to return the used space in MB? The PowerCLI VirtualMachineImpl
object has no UsedSpaceMB
property. This is where you can use a calculated property. A calculated property is a PowerShell hash table with two elements: Name
and Expression
. The Name
element contains the name that you want to give the calculated property. The Expression
element contains a scriptblock with PowerCLI code to calculate the value of the property. To return the name and the used space in MB for all of your virtual machines, run the following command:
PowerCLI C:\> Get-VM | >> Select-Object -Property Name, >> @{Name="UsedSpaceMB";Expression={1KB*$_.UsedSpaceGB}} >>
The hash table contains two key-value pairs. In the first element, the key is Name
and the value is UsedSpaceMB
. In the other element, the key is Expression
and the value is {1KB*$_.UsedSpaceGB}
. The special variable $_
is used to represent the current object in the pipeline. 1KB
is a PowerShell constant that has the value 1024
. In calculated properties, you can abbreviate the Name
and Expression
names to N
and E
.
Another example of a calculated property shows you how to return the aliases of all of the cmdlets that are the same for all of the providers:
PowerCLI C:\> Get-Command -Noun Item,ChildItem,Content,ItemProperty | >> Select-Object -Property Name, >> @{Name="Aliases";Expression={Get-Alias -Definition $_.Name}} >> Name Aliases ---- ------- Add-Content ac Clear-Content clc Clear-Item cli Clear-ItemProperty clp Copy-Item {copy, cp, cpi} Copy-ItemProperty cpp Get-ChildItem {dir, gci, ls} Get-Content {cat, gc, type} Get-Item gi Get-ItemProperty gp Invoke-Item ii Move-Item {mi, move, mv} Move-ItemProperty mp New-Item ni New-ItemProperty Remove-Item {del, erase, rd, ri...} Remove-ItemProperty rp Rename-Item {ren, rni} Rename-ItemProperty rnp Set-Content sc Set-Item si Set-ItemProperty sp
The first command is the Get-Command
statement that you have seen before; this returns the cmdlets that are the same for all of the providers. In the calculated property, the Get-Alias
cmdlet is used to get the aliases of these commands.