PowerShell Can Yield Unexpected Results

by Doug Finke on December 26, 2013

in Dynamic Languages,Microsoft,PowerShell

PowerShell let’s you easily move from adhoc to formal. Starting at the command line, trying things out, moving the details into a file and a function, adding parameters, typing the variables and more.

PowerShell Can Guess Wrong

A simple function, you pass 123 and expect the result 6 but it returns 150.

  • So where does the coercion go wrong?
  • How many coercions happen?
  • How do we fix it?
function SumDigits([uint32]$digits) {            
                
    $s   = $digits.ToString()            
    $sum = 0            
                
    for($idx = 0; $idx -lt $s.Length; $idx += 1) {            
        $sum += $s[$idx]                            
    }            
                
    $sum            
}

What Happened

What do you think?

SumDigits 123            
            
# Prints            
150 # Expected 6

I’ll follow up in my next post.

{ 1 comment… read it below or add one }

Nitesh 04.12.14 at 2:31 pm

That’s because $s[$idx] is of CHAR data type.
Hence instead of performing 1+2+3, Powershell is performing 49+50+51 (ASCII values of 1,2 and 3 respectively).

$sum += [string]$s[$idx] can be used to avoid this.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>