Sonntag, 17. Januar 2010

Eval-Min, Eval-Max, $null Part II

# The following relations are valid            
# All PowerShellStatements eval to True

# -2 < -1 < NULL < 0 < 1 < 2

-2 -lt -1
-1 -lt $null
$null -lt 0
0 -lt 1
1 -lt 2

$null -lt 1

# 2 > 1 > 0 > NULL > -1 > -2

2 -gt 1
1 -gt 0
0 -gt $null
$null -gt -1
-1 -gt -2

1 -gt $null


# 0 is not NULL

0 -ne $null
$null -ne 0

function Eval-Max
{
$max = $null
foreach ($i in $args){
if ($i -ne $null){
if( $i -gt $max -or $max -eq $null){
$max = $i
}
}
}
$max
}

function Eval-Min
{
$min = $null
foreach ($i in $args){
if ($i -ne $null){
if( $i -lt $min -or $min -eq $null){
$min = $i
}
}
}
$min
}

# $null handeled korrect

Eval-Min $null -1
Eval-Max $null -1
Eval-Min -1 $null
Eval-Max -1 $null


# The following seem wrong

Eval-Min -2 -1
Eval-Max -2 -1


To understand what happens look at

function Show-Type (){             
($args[0]).gettype()
}
Show-type 1
Show-type -1

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
True True String System.Object



I find this different behaviour is rather confusing. May we call it a bug?

When you cast the arguments to integers, you get the expected result.

Eval-Min $([int]-2) $([int]-1)            

-2


When you are working with properly typed input, the functions work as aspected.

1 Kommentar:

  1. You get the weird type results because a dash starts any Parameter name. So "-2" after a Command looks like a parameter name. If you put the value in parenthesis it will go back to script parsing.

    Eval-Min (-2) (-1)

    You sould make it an advanced fuction to make things easier.

    Eval-Min (-2,-1)

    AntwortenLöschen