Unable to highlight a value in Hashtable

Hi All,

I am using below command to extract the server disk space and using hashtable to customize the output.

gwmi -Class win32_logicaldisk | 
select Deviceid,
@{n='TotalSize' ; e={$_.size/1gb -as [int] } },
@{n='FreeSize in GB' ; e={$_.freespace/1gb -as [int] } }, 
@{n='FreeSpace in %' ; e={ ($_.freespace/$_.size) . tostring ("P") } } | Format-Table

Now with the below command when I am trying to highlight the value (Freespace in %) column if its below 10%, its not working. Looks like the if condition is not working in hash table, as only else condition is getting applied even if the space is below 10%.

gwmi -Class win32_logicaldisk | 
select Deviceid,
@{n='TotalSize';e={$_.size/1gb -as [int]}},
@{n='FreeSize in GB';e={$_.freespace/1gb -as [int]}},
@{n='FreeSpace in %';e={ if(($_.freespace/$_.size).tostring("P") -le '10%'){Write-Host (($_.freespace/$_.size).tostring("P")) -ForegroundColor Red} Else {($_.freespace/$_.size).tostring("P")}}}|Format-Table

Kindly advise.

Gaurav

Before we proceed - could you please format your code as code? Without that it’s going to be hard to copy and review it. Please edit your existing post - do not create a new one.

Thanks in advance. :wink:

Thanks Olaf, have tried to modify the format.

No … there’s an icon on the formatting bar of the post editor … :wink:

image

Thanks again for guiding, was not aware of this feature. Have modified.

Ah ok … I see … There’s no easy or builtin way to achieve what you’re trying to do. You cannot mix automatically by PowerShell formatted output with parts of it with Write-Host. Something like this has been asked a thousand times already and it does not work as you might think it does.

You would need to parse the output and reformat each single line again with Write-Host. Most of the times it’s just not worth it. :wink:

Of course you can still filter the output for the disks with less than 10% and limit the output to these particular disks. Or you could sort it for the “FreeSpace in %” and make it more obvious this way. Or you could add another property only showing if the free space is less than 10%. There are a lot of ways to “highlight” certain properties without using color. :wink:

1 Like

So does condition works in hashtables?

It works but you cannot use it to change the color of the output this way.

Try this:

Get-CimInstance -ClassName win32_logicaldisk | 
Select-Object Deviceid,
@{Name = 'TotalSize'; Expression = { $_.size / 1gb -as [int] } },
@{Name = 'FreeSize in GB'; Expression = { $_.freespace / 1gb -as [int] } },
@{Name = 'FreeSpace in %'; Expression = { if ($_.freespace / $_.size -le .1) {'Uncool ' + ($_.freespace / $_.size).tostring('P')} Else {'  Cool ' + ($_.freespace / $_.size).tostring('P') } } } 
1 Like