PowerShell Calculated Properties
A calculated property is a new property built by a small expression when you select it. It lets you rename a property or add a computed value without changing the original item.
Rename a property
Give the old Name a new Title. Print only the new Title value.
Set-Content -Path 'notes.txt' -Value 'hello'
$file = Get-Item 'notes.txt'
$renamed = $file | Select-Object @{Name='Title'; Expression={$_.Name}}
$renamed.TitleCompute a size in kilobytes
The file holds 1023 letters. Set-Content adds a newline, so the file is 1024 bytes long, which is 1 kilobyte.
Set-Content -Path 'notes.txt' -Value ('x' * 1023)
$file = Get-Item 'notes.txt'
$file.Length
$sized = $file | Select-Object @{Name='SizeKB'; Expression={$_.Length / 1024}}
$sized.SizeKBUpper-case a name with an expression
The expression can call a method on the old value. Here it upper-cases the file name.
Set-Content -Path 'notes.txt' -Value 'hello'
$file = Get-Item 'notes.txt'
$upper = $file | Select-Object @{Name='UpperName'; Expression={$_.Name.ToUpper()}}
$upper.UpperNameExample
Set-Content -Path 'notes.txt' -Value ('x' * 1023)
$file = Get-Item 'notes.txt'
$result = $file | Select-Object @{Name='FileName'; Expression={$_.Name}}, @{Name='SizeKB'; Expression={$_.Length / 1024}}, @{Name='UpperName'; Expression={$_.Name.ToUpper()}}
$result.FileName
$result.SizeKB
$result.UpperNameKey points
- Calculated property: a new property built by a small expression at selection time.
- Use a hashtable with Name and Expression to build one.
- The Name entry sets the name of the new property.
- The Expression entry holds code in braces that computes the value.
- Use $_ inside the Expression entry to refer to the current item.
- Use Select-Object with a calculated property to rename a property or add a new one.
In this example, the script creates notes.txt, selects three calculated properties from it at once, and then prints each new value in turn: the file name, its size in kilobytes, and its upper-cased name.
Note
a calculated property is computed when Select-Object runs, not stored on the original item.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which hashtable renames Name to Title?