官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 新蔡县| 泌阳县| 宁阳县| 麻城市| 余江县| 高平市| 淳化县| 正宁县| 仁寿县| 吉水县| 吴忠市| 怀集县| 峨边| 松潘县| 利辛县| 道孚县| 伊通| 嘉禾县| 新巴尔虎左旗| 饶阳县| 揭阳市| 区。| 浦城县| 凤凰县| 同德县| 二连浩特市| 丰都县| 荔波县| 镇坪县| 舒兰市| 长沙县| 西昌市| 志丹县| 宣武区| 乌兰县| 三穗县| 岑巩县| 建宁县| 卢氏县| 凤山县| 进贤县|