none
Defragmentation: Audit fragmentation of attached hard drives (Fixed local disks only)

    Question

  • I am attempting to create a script to list all drives attached to the system identified as type 3, eg "Fixed Local Disk", and then to audit them for their current fragmentation status.

    Thus far, I am able to list all local disks 

    Get-WmiObject -Class win32_volume | Where-Object { $_.drivetype -eq 3 -and $_.driveletter -ne $null } | ft -Property DriveLetter

    This presents me with the info I need, however the next phase, where I am attempting to pass through the command "Defrag driveletter /a"

    For the life of me, I cannot get it to pass drive letters to run the analysis. 

    Get-WmiObject -Class win32_volume | Where-Object { $_.drivetype -eq 3 -and $_.driveletter -ne $null } | defrag $_.driveletter /a

    That is the code I have, though not functional, it does not like my use of $_ to try to pass the drive letter through the pipe. 

    Tuesday, April 18, 2017 11:58 PM

Answers

  • Get-WmiObject -Class win32_volume | 
    	Where-Object {
    		$_.DriveLetter -and $_.drivetype -eq 3
    	} |
    	ForEach-Object{
    		defrag $_.driveletter /a
    	}


    \_(ツ)_/

    • Marked as answer by Swat1234 Wednesday, April 19, 2017 4:27 PM
    Wednesday, April 19, 2017 12:04 AM

All replies

  • Get-WmiObject -Class win32_volume | 
    	Where-Object {
    		$_.DriveLetter -and $_.drivetype -eq 3
    	} |
    	ForEach-Object{
    		defrag $_.driveletter /a
    	}


    \_(ツ)_/

    • Marked as answer by Swat1234 Wednesday, April 19, 2017 4:27 PM
    Wednesday, April 19, 2017 12:04 AM
  • Or this:

    Get-WmiObject -Class win32_volume | 
    	Where-Object {
    		$_.DriveLetter -and $_.drivetype -eq 3
    	} |
    	ForEach-Object{
    		$results = $_.DefragAnalysis()
    		[pscustomobject]@{
    			Drive = $_.Driveletter
    			DefragRecommended = $results.DefragRecommended
    			DefragAnalysis = $_.DefragAnalysis
        	}
    	}
    


    \_(ツ)_/

    Wednesday, April 19, 2017 12:13 AM
  • Or this:

    Get-WmiObject -Class win32_volume | 
    	Where-Object {
    		$_.DriveLetter -and $_.drivetype -eq 3
    	} |
    	ForEach-Object{
    		$results = $_.DefragAnalysis()
    		$results.DefragAnalysis | Add-Member NoteProperty DriveLetter $_.Driveletter -PassThru
    	} | 
    	Select-Object Driveletter, TotalExcessFragments, TotalFragmentedFiles, TotalPercentFragmentation
    


    \_(ツ)_/

    Wednesday, April 19, 2017 12:17 AM
  • Thank you so much! that is exactly what I was looking for!
    Wednesday, April 19, 2017 4:28 PM