Home > database >  calculate free disk space percentage powershell
calculate free disk space percentage powershell

Time:10-26

I am trying to get the free percentage like present in Disk Management

$Diskmgmt = Get-Volume | select DriveLetter,FileSystemLabel,FileSystem,DriveType,HealthStatus,OperationalStatus,SizeRemaining,Size

foreach($dsk in $Diskmgmt)
{

    $dl = $dsk.DriveLetter
    $fsl = $dsk.FileSystemLabel
    $fs = $dsk.FileSystem
    $dt = $dsk.DriveType
    $hs = $dsk.HealthStatus
    $os = $dsk.OperationalStatus
    $sizer = [math]::round($dsk.SizeRemaining /1Gb, 2)
    $siz = [math]::round($dsk.Size /1Gb, 2)
    $PercentFree =  [Math]::Round(($sizer / $siz) * 100, 2)

but the calculation coming like below

Capacity     Free Space %Free
154.82 GB     200 GB     77 % 
0 GB          0 GB       77 % 
1.96 GB       6 GB       33 % 
0.15 GB       0.49 GB    31 % 
52.32 GB      99.51 GB   53 % 
11.19 GB      11.23 GB   100 % 
9.95 GB       10 GB      99 % 

Please let me know if I am doing it correctly.

CodePudding user response:

Using get-psdrive and the 'p' format specifier:

get-psdrive c | % { $_.free/($_.used   $_.free) } | % tostring p

9.24%

CodePudding user response:

I'm guessing you're looking for something like this:

$props = @(
    'DriveLetter'
    'FileSystemLabel'
    'FileSystem'
    'DriveType'
    'HealthStatus'
    'OperationalStatus'
    @{n='SizeRemaining';e={"{0:N3} Gb" -f ($_.SizeRemaining/ 1Gb)}}
    @{n='Size';e={"{0:N3} Gb" -f ($_.Size / 1Gb)}}
    @{n='% Free';e={"{0:P}" -f ($_.SizeRemaining / $_.Size)}}
)
Get-Volume -DriveLetter C, D | Select-Object $props | Format-Table

As an example this is how it looks on my laptop for Drives C and D:

DriveLetter FileSystemLabel FileSystem DriveType HealthStatus OperationalStatus SizeRemaining Size       % Free
----------- --------------- ---------- --------- ------------ ----------------- ------------- ----       ------
          D                 NTFS       Fixed     Healthy      OK                748.731 Gb    931.512 Gb 80.38%
          C                 NTFS       Fixed     Healthy      OK                170.959 Gb    236.764 Gb 72.21%
  • Related