Search code examples
powershellcommandpowershell-remoting

How to get only the device name and the free space percentage WITHOUT the property field?


I have a command that returns the DeviceID and the free space percentage as follows:

    $devices= Get-CimInstance -Class Win32_LogicalDisk -Filter "Drivetype=3" | Select-Object  DeviceID, @{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}}
    Write-Output $devices

The output is good, as follows:

DeviceID       : C:
Free (%)       :   33 %
PSComputerName : MIKAELCOMP
RunspaceId     : c2b02166-4e08-4e90-b8f5-5defafa20ac9

DeviceID       : D:
Free (%)       :   22 %
PSComputerName : MIKAELCOMP
RunspaceId     : c2b02166-4e08-4e90-b8f5-5defafa20ac9

HOWEVER, I need the output to be like this:

C: 33%
D: 22%

As you see, without the description in the first column.

Any way to do that?

(also, I don't know why I'm getting the last two fields: PSComputerName and RunspaceId).

THANKS.


Solution

  • You may use the string format operator (-f) for this:

    $devices | ForEach-Object {
        "{0} {1}" -f $_.DeviceID,$_.'Free (%)'.Trim()
    }
    

    Trim() is used to remove the preceding and trailing spaces you may have for your percentage values. TrimStart() can be used to only remove preceding spaces. TrimEnd() can be used to only remove trailing spaces.