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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With