C Drive % Space Remaining

So based off of this code and this code, I still can’t figure out a way to get the % space remaining on my C drive as just a simple number.

I tried this but errors out of course:

$var1 = Get-CimInstance -ClassName CIM_logicaldisk -Filter "DeviceID='C:'" | Select-Object -property FreeSpace
$var2 = Get-CimInstance -ClassName CIM_logicaldisk -Filter "DeviceID='C:'" | Select-Object -property Size
$var3 = $var1 / $var2

Write-Host = "% space Remaining on C drive:",$var3

I’d even settle for this, with the space remaining and not the percentage:

Get-CimInstance -ClassName cim_logicaldisk -Filter "DeviceID='C:'" | Where-Object {$_.FreeSpace} | Select-Object @{n='FreeSpace';exp={"{0:N2} GB" -f ($_.FreeSpace / 1GB)}}

but I can’t seem to get the actual ‘number’ into a variable so I can perform a calculation on it. If I set that last bit of code equal to $var1, $var1 contains “@{FreeSpace=78.18 GB}”

I figured out the code after “Select-Object” formats the result in some way but I haven’t found a tutorial or example on the options that could be used. I’m a bit hopeless lol.

Your help is much appreciated! Thanks!

I’m not completely sure what exactly a simple number is for you but it is actually not that hard:

Get-CimInstance -ClassName CIM_LogicalDisk | 
    Select-Object -Property DeviceID,Size,FreeSpace,@{Name = 'FreeSpaceInPercentAsSimpleNumber';Expression ={$_.FreeSpace / $_.Size * 100}}

So to get really just this one result in a variable you simply do this:

$var1 = 
    (Get-CimInstance -ClassName CIM_logicaldisk -Filter "DeviceID='C:'" | 
        Select-Object @{Name = 'FreeSpacePercent'; Expression = { $_.FreeSpace / $_.Size * 100 }}).FreeSpacePercent
$var1
1 Like

As always your solution is perfect! Me saying “simple number” was to say, just wanted a number. Whatever I was doing I had additional info stuffed into the variable so when I tried to perform a calc, well, you know. :slight_smile:

So it’s probably time for me to get a good book on powershell. Anything you’d recommend?

A short forum search brought this up …

… and maybe this …

1 Like