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

I was hoping someone could help me 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:

 MyField : 1234 

I expected, however:

 MyField : 1,234.00 

The expected result will be returned if I add value brackets around 1234:

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

Formatting also works without evaluation brackets if called directly, and not in the shell of the Get-FormattedNameValuePair function.

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

Can someone explain the behavior above?

+6
source share
1 answer

I can not play it 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 reproduce this on V2. If you change the cast of [object] to [int] , it will start working as you expect. There's something about putting this in an object that causes a problem. This error can be shown somewhat more succinctly:

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

There are a number of known issues in V2 related to wrapping .NET types in the PowerShell extended type system type, known as PSObject. It looks like this problem. And indeed, it is connected. Check this:

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

If you expand the object to return to the original, you will get the expected result. Drop it to V2 error, which, fortunately, has been fixed in V3.

+5
source

Source: https://habr.com/ru/post/926522/


All Articles