Help with a custom object

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Scott Windmiller Scott Windmiller 3 months, 2 weeks ago.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #43653
    Profile photo of Scott Windmiller
    Scott Windmiller
    Participant

    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

    #43657
    Profile photo of Craig Duff
    Craig Duff
    Participant
    "$([math]::round($_.FreeSpace / $_.Capacity * 100))%"

    Try that inside the expression

    #43659
    Profile photo of random commandline
    random commandline
    Participant

    Use the format operator.

    @{n='PercentFree';exp={"{0}%" -f [math]::round($_.FreeSpace / $_.Capacity * 100) }}
    
    #43676
    Profile photo of Scott Windmiller
    Scott Windmiller
    Participant

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

    #43695
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    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 3 months, 2 weeks ago by Profile photo of Paal Braathen Paal Braathen.
    • This reply was modified 3 months, 2 weeks ago by Profile photo of Paal Braathen Paal Braathen.
    #43701
    Profile photo of Scott Windmiller
    Scott Windmiller
    Participant

    Thanks!!!

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.