Help with a custom object

Welcome Forums General PowerShell Q&A Help with a custom object

This topic contains 5 replies, has 4 voices, and was last updated by

 
Participant
2 years, 5 months ago.

  • Author
    Posts
  • #43653

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member
    "$([math]::round($_.FreeSpace / $_.Capacity * 100))%"

    Try that inside the expression

  • #43659

    Participant
    Points: 10
    Rank: Member

    Use the format operator.

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

      Participant
      Points: 0
      Rank: Member

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

  • #43695

    Participant
    Points: 0
    Rank: Member

    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 🙂

  • #43701

    Participant
    Points: 0
    Rank: Member

    Thanks!!!

The topic ‘Help with a custom object’ is closed to new replies.