In PowerShell (5.1.14393.1944), when I have a varibale with a value of $null
, a ForEach-Object
loop attempts to iterate over the object, causing undesired results.
In this examaple, I am attempting to retrun the highest maximum result from a set of data. However, if there is no data, -1
should be returned.
function Get-MaximumResult
{
param(
[parameter(Mandatory,Position=0)]
[AllowNull()]
[object]$MetricsData
)
if (-not($MetricsData)) { Write-Host "Debug: Variable is null" }
[int]$maximum = -1
$MetricsData | ForEach-Object {
if ([int]$_.maximum -gt $maximum) { $maximum = [int]$_.maximum }
Write-Host "Debug: Maximum: $maximum"
}
return $maximum
}
Get-MaximumResult -MetricsData $null
The output generated is as follows -
Debug: Variable is null
Debug: Maximum: 0
0
What I would expect to see is this -
Debug: Variable is null
-1
I have found a couple of similar questions from a few years ago, however the answers indicate that this bug was fixed in version 3. Has anyone else experienced this bug?