I want PowerShell to throw an error when trying to select non-existing properties, but instead I get empty column as output. Example:
$ErrorActionPreference=
PowerShell expanding non-existing properties to $null behaves as designed. AFAICS the only thing you could do is to explicitly check if all properties exist:
$props = 'Id', 'ProcessName', 'xxx'
$p = Get-Process *ex*
$missing = $p | Get-Member -Type *property |
Select-Object -Expand Name |
Compare-Object -Reference $props |
Where-Object { $_.SideIndicator -eq '<=' } |
Select-Object -Expand InputObject
if ($missing) {
throw "missing property $missing."
} else {
$p | Select-Object $props
}
Of course you could wrap this in a custom function:
function Select-ObjectStrict {
[CmdletBinding()]
Param(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]$InputObject,
[Parameter(
Position=1,
Mandatory=$true
)][string[]]$Property
)
Process {
$missing = $InputObject | Get-Member -Type *property |
Select-Object -Expand Name |
Compare-Object -Reference $Property |
Where-Object { $_.SideIndicator -eq '<=' } |
Select-Object -Expand InputObject
if ($missing) {
throw "missing property $missing."
} else {
$InputObject | Select-Object $Property
}
}
}
so it could be used like this:
Get-Process *ex* | Select-ObjectStrict -Property 'Id', 'ProcessName', 'xxx'