Today on PoshBytes, we are going to look at creating custom properties right in the pipeline with Select-Object.
This post is a companion for the video embedded below. Scroll down to see the code from the video.
PoshBytes: Select-Object With Custom Properties (Because Plain Properties Are Boring)
Select-Object lets you choose and create custom properties directly in the pipeline.
Example with object properties
Select specific built-in properties.
Get-ChildItem C:\Temp | Select-Object Name, Length
Example with calculated property
Perform calculations directly in the pipeline.
Get-ChildItem C:\Temp | Select-Object Name,
{[math]::Round($_.Length / 1MB, 2)}
Example with calculated property and name
Label your calculated properties using Name and Expression.
Get-ChildItem C:\Temp | Select-Object Name,
@{Name='SizeMB';Expression={[math]::Round($_.Length / 1MB, 2)}}
Example with mixed data
Expressions can call any command, but not all should be used this way.
$Folder = 'C:\Temp'
Get-ChildItem $Folder | Select-Object Name,
@{Name='Folder';Expression={$Folder}},
@{Name='QueryData';Expression={Get-Date}},
@{Name='Content';Expression={Get-Content -Path $_.FullName}}
Example with error in Select-Object causing null output
Divide-by-zero errors inside expressions can produce null output without visible errors.
[math]::Round(1 / 0, 2)
Get-ChildItem C:\Temp | Select-Object Name,
@{Name='SizeMB';Expression={[math]::Round($_.Length / 0, 2)}}
Use Select-Object to display custom output, compute new columns, and name them clearly.
• Select-Object can calculate properties via script blocks.
• Use @{ Name = 'Column'; Expression = { … } } to add labels.
• Calculated expressions run per object.
• Great for formatting, math, and derived values.
• Errors inside Select-Object can yield empty output.