PowerShell for Windows Admins

Feb 8 2010   2:10PM GMT

Defragmenting a volume



Posted by: Richard Siddaway
Tags:
Disks

 

We have seen how to analyse a volume to see if it needs a defrag.  This is how we do it.  Modern windows systems will do a certain amount of defrag work automatically but sometimes we need to help them out.

 

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
028
029
030
031
032
function Start-Defrag {
[CmdletBinding(SupportsShouldProcess=$true)]
param ([string]$computer=".",
       [string]$drive
)
    if ($drive -notlike "?:"){ 
    Throw "Drive should be submitted as letter and colon e.g. C:"}
   
    $filt = "Name=’" + $drive + "\\’"
    $vol = Get-WmiObject -Class Win32_Volume -Filter $filt `
    -ComputerName $computer
   
    $res = $vol.Defrag($false)
   
    if ($res.ReturnValue -eq 0) {
        Write-Host "Defrag succeeded"
        $res.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 "Defrag failed Result code: " $res.ReturnValue}
}

 

Our function has a computer name and drive as parameters. We check the drive is in the right format and reject if it isn’t.

From that its just a case of getting a WMI object for the volume and calling the defrag method.  The $false parameter means don’t automatically fix problems – we want to deal with those ourselves.

If the return value is 0 – we have a winner and our defrag succeeded. Time to see the results other wise we dump out the return code so we can find out what went wrong

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: