Search code examples
powershellhard-drivesolid-state-drive

Defrag system hdd only if is mechanical disk


we needed some help. in practice we were looking for a method to start the defremmentation (defrag) of the primary disk (on windows "C:") only if it is a HDD and not an SSD we read about the command in powershell but can't compile (mediaType)


Solution

  • This script should work for you:

    #Get friendly name of the C drive
    $name = (get-partition -DriveLetter C | get-disk).FriendlyName
    
    #Use friendly name to determine drive type
    $mediatype = (Get-PhysicalDisk -FriendlyName $name).MediaType
    
    #Defragment drive if drive type is HDD
    
    if ($mediatype -eq "HDD")
        {
            Optimize-Volume -DriveLetter C
        }