Gary Allen
Gary Allen

Reputation: 170

Get Disk Usage in PowerShell

I am trying to get the current disk usage activity and display it in an xaml form. I have attempted to google how to do it, but everyone just talks about MB's available/used. I want to display the percentage shown of disk active time in task manager for windows 10.

I have attempted to find a way to grab the info with Get-Counter as well as collect1 but neither of these seem work and I am lost on a starting point.

Upvotes: 2

Views: 12050

Answers (1)

Gary Allen
Gary Allen

Reputation: 170

I did actually find a solution eventually. I was looking for Disk Active Time not usage. There is no way to grab the information easily, but I found some code online which I was able to modify to my needs. I cannot remember the source otherwise I would site it.

$Sleep=10
$Idle1=$DiskTime1=$T1=$Idle2=$DiskTime2=$T2=1

$Disk = Get-WmiObject -class Win32_PerfRawData_PerfDisk_LogicalDisk `
-filter "name= 'C:' "
[Double]$Idle1 = $Disk.PercentIdleTime
[Double]$DiskTime1 = $Disk.PercentDiskTime
[Double]$T1 = $Disk.TimeStamp_Sys100NS

start-Sleep $Sleep

$Disk = Get-WmiObject -class Win32_PerfRawData_PerfDisk_LogicalDisk `
-filter "name= 'C:' "
[Double]$Idle2 = $Disk.PercentIdleTime
[Double]$DiskTime2 = $Disk.PercentDiskTime
[Double]$T2 = $Disk.TimeStamp_Sys100NS

$PercentIdleTime =[math]::Round((($Idle2 - $Idle1) / ($T2 - $T1)) * 100)
$PercentDiskTime =[math]::Round((($DiskTime2 - $DiskTime1) / ($T2 - $T1)) * 100)

$PercentDiskTime reflects what you see in the graph on Task Manager as the Active time best. Adjusting $Sleep can provide an avg over time. I find anything longer than 10 seconds and under 3 is too inaccurate for real time data.



For anyone who comes to the question looking for actual Disk Usage as a percentage:

[string[]]$Computer = $env:COMPUTERNAME
$Disk = Get-WMIObject Win32_Logicaldisk -filter "deviceid='C:'"
$FreeSpacePer = ((($Disk.Freespace /1Gb -as [float]) / ($Disk.Size / 1Gb -as [float]))*100) -as [int]
$SpaceUsePer = 100 - $FreeSpacePer

Upvotes: 3

Related Questions