Author Posts

June 16, 2016 at 7:22 pm

This is probably a really simple answer but I cannot figure out what I am doing wrong. I have this code:

Select Name, @{ n = 'FreeSpace'; e = { [int]($_.FreeSpace/1GB) } },
		   @{ n = 'Capacity'; e = { [int]($_.Capacity/1GB) } },
		   @{ n = 'PercentFree'; e = { [math]::round($_.FreeSpace / $_.Capacity * 100) } },

and this works fine. The only thing I want to do is add a % sign after the value of "PercentFree" and I just don't know the correct syntax.
I tried:

@{ n = 'PercentFree'; e = { [math]::round($_.FreeSpace / $_.Capacity * 100) } '%' },

but know that does not even look right, let alone work...lol

Thanks,
Scott

June 16, 2016 at 7:27 pm

"$([math]::round($_.FreeSpace / $_.Capacity * 100))%"

Try that inside the expression

June 16, 2016 at 8:15 pm

Use the format operator.

@{n='PercentFree';exp={"{0}%" -f [math]::round($_.FreeSpace / $_.Capacity * 100) }}

June 16, 2016 at 11:39 pm

Thanks, this worked great! I didn't even know about the format operator.

June 17, 2016 at 7:05 am

Thought this could be worth mentioning:

You don't need to one-line the statement in the expression part. It's a full script block and you could write more complex stuff on multiple lines (or with semicolons):

PS M:\> Get-Item . | Select-Object @{n="Test"; e={$x=123; $y=321; $z = (Test-Connection "powershell.org" -Count 2 | Measure-Object -Property "ResponseTime" -Sum).Sum; $x + $y + $z}}

Test
—-
444

It might hurt the readability if you put many things in the expression, but the possibility is there 🙂

  • This reply was modified 2 years, 4 months ago by  Paal Braathen.
  • This reply was modified 2 years, 4 months ago by  Paal Braathen.