Monday, October 29, 2012

Read-Host that is not assigned to a variable is added to return value

The best way I can illustrate this is as follows. Given this code for test.ps1:

Read-Host "Hit enter to continue"

try {
    throw system.exception
} catch {
    return $null
}

When I call test.ps1 I can expect a $null value, right? No. This is what happens:

> $a=.\test.ps1
Hit enter to continue:
> $a

> $a -eq $null
>
> $a.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array


> $a.Count
2
> $a[0]

> $a[1]
> $a[1] -eq $null
True

One would expect $a -eq $null to be true. Instead, $a is an array where the first value is that of Read-Host and the second value is the expected $null. 

So, I changed my code to the following:

$HitEnter = Read-Host "Hit enter to continue"

try {
    throw system.exception
} catch {
    return $null
}

Now everything works as expected:

> $a=.\test.ps1
Hit enter to continue:
> $a -eq $null

[Update 2013-05-27] Aha - found the reason behind this. Uncaptured output is still returned as output. Reference: Function Output Consists of Everything That Isn’t Captured

No comments:

Post a Comment