2

PowerShell script runs a command to give me total bytes and total free bytes of my harddisk. I want to pick those two returned values as variables to do some calculations with but I'm not sure how to set a variable to a specific part of a command's output.

After looking through similar questions I cant apply the same logic to my situations. I have never used PowerShell before and not very familiar with Windows servers. Any recommended tutorials would be welcomed.

fsutil volume diskfree C:

Total # of free bytes : 1234567

Total # of bytes: 7654321

3 Answers 3

3

I would instead use PowerShell's Get-WmiObject command and look at the Win32_LogicalDisk class. You could do something like this:

$cDrive = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceId='C:'"

That way you can get the free space and size attributes of the drive and manipulate them however you like. For example, this would show you the free space on the C drive in GB:

[Math]::Round( $cDrive.FreeSpace / 1GB)
Sign up to request clarification or add additional context in comments.

2 Comments

Would i be able to use this output to get the percentage of free space? (Freespace/Size)*100 = percent
@a.smith Yes [grin]. $percentFree = ( $cDrive.FreeSpace / $cDrive.Size) * 100
3

You can use WMI from Powershell.

$diskData = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object Size, FreeSpace

Write-Host $diskData.Size
Write-Host $diskData.FreeSpace

1 Comment

This helped me a lot. The ability to separate the integer value from the variable name!
2

Get-WmiObject as mentioned in the other answers is the way to go but for the fun of it

$freespace, $size = [int64[]]((fsutil volume diskfree C:)[0,1] -split ': ')[1,3]
Write-Output $freespace, $size

Disclaimer: note that this breaks when microsoft decides to change the output format of fsutil

1 Comment

Thanks, useful to know how to pick values from a command but yes i will go with Get-WmiObject as above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.