- Learning PowerCLI
- Robert van den Nieuwendijk
- 366字
- 2021-07-19 18:22:31
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.
- Applied Unsupervised Learning with R
- 電腦維護與故障排除傻瓜書(Windows 10適用)
- SDL Game Development
- 辦公通信設備維修
- 單片機原理及應用系統設計
- Artificial Intelligence Business:How you can profit from AI
- micro:bit魔法修煉之Mpython初體驗
- CC2530單片機技術與應用
- Practical Machine Learning with R
- 深入理解序列化與反序列化
- 基于Proteus仿真的51單片機應用
- Blender Quick Start Guide
- 微控制器的應用
- 嵌入式系統設計大學教程(第2版)
- 電腦主板維修技術