PowerShell for Windows Admins

Feb 6 2010   1:22PM GMT

Defrag Analysis Part 2

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Last time we saw how to check whether a single volume needs a defrag run.  Usually our servers have a number of volumes – ideally we want to check all of them together

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
function Test-Defrag {
[CmdletBinding(SupportsShouldProcess=$true)]
param ([string]$computer=".")
    "`n $computer" 
    Get-WmiObject -Class Win32_Volume -ComputerName $computer | 
      where {$_.Name -like "?:\"} | 
      foreach {
       $_.Name
       $dfa = $_.DefragAnalysis()
     
       if ($dfa.DefragRecommended){
            $dfa.DefragAnalysis | Format-List AverageFileSize, 
            AverageFragmentsPerFile, AverageFreeSpacePerExtent, 
            ClusterSize,ExcessFolderFragments, FilePercentFragmentation, 
            FragmentedFolders, FreeSpace, FreeSpacePercent, 
            FreeSpacePercentFragmentation, LargestFreeSpaceExtent, 
            MFTPercentInUse, MFTRecordCount, PageFileSize, 
            TotalExcessFragments, TotalFiles, TotalFolders, 
            TotalFragmentedFiles, TotalFreeSpaceExtents, 
            TotalMFTFragments, TotalMFTSize, TotalPageFileFragments, 
            TotalPercentFragmentation, TotalUnmovableFiles, 
            UsedSpace, VolumeName, VolumeSize 
       }
       else {Write-Host "`t Drive does not need defrag at this time"}

    }
}

We has a function that we can give a computer name to as a parameter.  This then gets the volume information using the Win32_Volume class. We only accept volumes with names like c:\ and pass the results into a foreach.

Because we already have an object representing the volume we can use the DefragAnalysis method directly. If it indicates a defrag is necessary we dump out the results.

We could have continued with the Invoke-WmiMethod route we used previously but it would have been a bit complicated to code – lets keep it simple.

Technorati Tags: ,,

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: