Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: What is the difference between 1234 and (1234)?

I was hoping that someone could help me out with the following:

Function Get-FormattedNameValuePair([string] $name, [object] $value)
{
    return "$("{0,-24}" -f $name) : $("{0,15:N2}" -f $value)"
}

Write-Output (Get-FormattedNameValuePair -name MyField -value 1234)

The above returns:

MyField                  :            1234

I was expecting, however:

MyField                  :        1,234.00

The expected result is correcly returned if I add evaluation brackets around the 1234:

Write-Output (Get-FormattedNameValuePair -name MyField -value (1234))

The formatting also works without the evaluation brackets if called directly instead of wrapped within the 'Get-FormattedNameValuePair' function.

[string] $name = "MyField"
[object] $value = 1234
Write-Output  "$("{0,-24}" -f $name) : $("{0,15:N2}" -f $value)"

Can anyone explain the behavior above?

like image 531
Mike Rosenblum Avatar asked Sep 28 '12 16:09

Mike Rosenblum


1 Answers

I can't reproduce this on V3

Function Get-FormattedNameValuePair([string] $name, [object] $value)
{
    return "$("{0,-24}" -f $name) : $("{0,15:N2}" -f $value)"
}

Write-Output (Get-FormattedNameValuePair -name MyField -value 1234)

MyField                  :        1,234.00

But I can repro this on V2. If you change the [object] cast to [int] it starts working as you expect. There's something about putting this in an object that is causing the problem. This error can be shown a bit more succinctly like so:

function foo([object]$o) { "{0,15:N2}" -f $o }
foo 1234
       1234

In V2 there are a number of known issues related to the wrapping of .NET types in a PowerShell extended type system type known as PSObject. This looks to be related to that issue. And indeed it is related. Check this out:

function foo([object]$o) { "{0,15:N2}" -f $o.psobject.baseobject }
foo 1234
   1,234.00

If you unwrap the object to get back to the original, you get the expected output. Chalk this up to a V2 bug that is fortunately fixed in V3.

like image 138
Keith Hill Avatar answered Sep 28 '22 01:09

Keith Hill