Wednesday, August 29, 2007

Is my drive fragmented?

Marco Shaw commented on my post ragarding fragmentation of files. Unfortunately WMI doesn't expose the fragmentation of specific files (at least I can't find it). But Marco's approach is useful in many situations.

Here is a small example on how to retrieve and display the fragmentation staus from a series of servers:

$allservers = "server1.", "server2"

Write-Host -foregroundcolor Yellow "Server         Drive Label         ClusterSize AverageFragmentsPerFile"
Write-Host -foregroundcolor Yellow "-------------- ----- ------------ ----------- -----------------------"

foreach ($server in $allservers) {
    $allvolumes = Get-Wmiobject -class Win32_Volume -Computername $server
    foreach ($volume in $allvolumes) {
        if ($volume.drivetype -eq 3) {
            $output = "{0,-15} {1,-6} {2,-15} {3,8} {4,15}" -f $server, $volume.DriveLetter, $volume.Label, $volume.DefragAnalysis().DefragAnalysis.ClusterSize, $volume.DefragAnalysis().DefragAnalysis.AverageFragmentsPerFile
            Write-Host -foregroundcolor White $output
        }
    }
}

7 comments:

James said...

Forgive the formatting, but here is a revised script. You don't need to iterate $allservers, gwmi takes an array. If you pass directly to foreach, you can skip the variable creation and process the objects like this:

param([string[]]$allservers)

Get-Wmiobject -class Win32_Volume -Filter "DriveType='3'" -Computername $allservers | %{
new-object psobject |
add-member -pass NoteProperty Server $_.__server |
add-member -pass NoteProperty DriveLetter $_.DriveLetter |
add-member -pass NoteProperty Label $_.Label |
add-member -pass NoteProperty CLusterSize $_.DefragAnalysis().DefragAnalysis.ClusterSize |
add-member -pass NoteProperty AverageFragmentsPerFile $_.DefragAnalysis().DefragAnalysis.AverageFragmentsPerFile
}

Anonymous said...

Guys,

How can I use this powershell script to identify fragmentation on a drive level? I want to do this for my SQLServers...

Jakob Bindslet said...

I'm not sure what you are asking. Both of the above scripts can be used to display fragmentation on each volume on a server ...

Tsubaki said...

is this for windows vista only?

Have you tried it in xp?

Jakob Bindslet said...

Win32_volume isn't available in Windows XP, so it only works in Windows 2003 or higher - I'm not quite sure about vista either.

Anonymous said...

Could not find a suitable section so I written here, how to become a moderator for your forum, that need for this?

Anonymous said...

yo. thanks for