07-21-2023, 08:44 PM
I often have the following situation in my PowerShell code: I have a function or property that returns a collection of objects, or `$null`. If you push the results into the pipeline, you also handle an element in the pipeline if `$null` is the only element.
Example:
$Project.Features | Foreach-Object { Write-Host "Feature name: $($_.Name)" }
If there are no features ($Project.Features returns $null), you will see a single line with "Feature name:".
I see three ways to solve this:
if ($Project.Features -ne $null)
{
$Project.Features | Foreach-Object { Write-Host "Feature name: $($_.Name)" }
}
or
$Project.Features | Where-Object {$_ -ne $null) | Foreach-Object {
Write-Host "Feature name: $($_.Name)"
}
or
$Project.Features | Foreach-Object {
if ($_ -ne $null) {
Write-Host "Feature name: $($_.Name)" }
}
}
But actually I don't like any of these approaches, but what do you see as the best approach?
Example:
$Project.Features | Foreach-Object { Write-Host "Feature name: $($_.Name)" }
If there are no features ($Project.Features returns $null), you will see a single line with "Feature name:".
I see three ways to solve this:
if ($Project.Features -ne $null)
{
$Project.Features | Foreach-Object { Write-Host "Feature name: $($_.Name)" }
}
or
$Project.Features | Where-Object {$_ -ne $null) | Foreach-Object {
Write-Host "Feature name: $($_.Name)"
}
or
$Project.Features | Foreach-Object {
if ($_ -ne $null) {
Write-Host "Feature name: $($_.Name)" }
}
}
But actually I don't like any of these approaches, but what do you see as the best approach?