PowerShell: Expand Disk Volume to Maximum Size

# expandDisk.ps1
# version 0.02

$driveLetters=(Get-wmiobject win32_volume -filter 'DriveType=3 AND DriveLetter IS NOT NULL').DriveLetter

function expandDiskMaxSize($driveLetters='c'){    
    $results=@()
    Update-HostStorageCache
    foreach($driveletter in $driveLetters){
        try{
            if($driveletter -match ':'){$driveletter=$driveLetter[0]}
            $existingSize=(Get-Partition -DriveLetter $driveLetter).Size            
            $max=(Get-PartitionSupportedSize -DriveLetter $driveLetter).SizeMax
            if($existingSize -lt $max){
                write-host "Resizing volume driver letter '$driveLetter' from $existingSize to $max bytes"
                Resize-Partition -DriveLetter $driveLetter -Size $max -ea SilentlyContinue
                # Update-HostStorageCache
                $newSize=(Get-Partition -DriveLetter $driveLetter).Size 
            }else{
                write-host "Volume drive letter '$driveLetter' is not less than its available maximum of $([math]::round($existingSize/1GB))GB. Volume not resized."
                $newSize=$existingSize
            }
            $results+=[pscustomobject]@{
                driveLetter=$driveletter
                previousSize="$([math]::round($existingSize/1GB))GB"
                currentSize="$([math]::round($newSize/1GB))GB"
            }
        }catch{
            write-warning $_
        }
    }
    return $results
}
 
expandDiskMaxSize $driveLetters
# expandDisk.ps1
# version 0.01

$driveLetter='c'

function expandDiskMaxSize($driveLetter='c'){    
    try{
        $existingSize=(Get-Partition -DriveLetter $driveLetter).Size
        Update-HostStorageCache
        $max=(Get-PartitionSupportedSize -DriveLetter $driveLetter).SizeMax
        if($existingSize -lt $max){
            write-host "Resizing volume driver letter '$driveLetter' to its available maximum of $([math]::round($max/1GB))GB"
            Resize-Partition -DriveLetter $driveLetter -Size $max -ea Stop
        }else{
            write-host "Volume driver letter '$driveLetter' is not less than its available maximum of $([math]::round($existingSize/1GB))GB. Volume not resized."
        }
        return $true
    }catch{
        write-warning $_
        return $false
    }
}

expandDiskMaxSize $driveLetter

Leave a Reply

Your email address will not be published. Required fields are marked *