Search code examples
windowspowershellwindows-server-2012

Shrink Automation


My script to push the OS partition resize, e.g.

Resize-Partition -DiskNumber 2 -PartitionNumber 1 -Size (60GB)

If I get an error because windows cannot shrink to the desired size ("there is not enough space to perform action") then try

Resize-Partition -DiskNumber 2 -PartitionNumber 1 -Size (70GB)

and the loop keeps going until the partition is resized.

Question is how do I set the conditions using pwshell?


Solution

  • Here is an overview of what you need to do:

    1. Set a variable to the desired size of the partition.
    2. Loop until you succeed or the desired size is the current size of the partition.
    3. In the loop, try to resize the partition to the size in the variable.
      • If the attempt fails, use some algorithm to move toward the actual size of the partition.

    Here is my code (you may want to save this to a .ps1 file and import it if you are new to PowerShell functions.)

    Function Resize-PartitionDynamic
    {
        param(
        [int] $diskNumber,
        [int] $PartitionNumber,
        [long] $Size
        )
    
        $currentSize = $size
        $successful = $false
        $maxSize = (get-partition -DiskNumber 0 -PartitionNumber 1).size
    
        # Try until success or the current size is 
        # the size of the existing partition
        while(!$successful -and $currentSize -lt $maxSize)
        {
            try
            {
                Resize-Partition -DiskNumber $diskNumber -PartitionNumber $PartitionNumber -Size $currentSize -ErrorAction Stop
                $successful = $true
            }
            catch
            {
                # Record the failure and move the size
                # half way to the size of the current partition
                # feel free to change the algorithm move closer to the
                # current size to something else... 
                # there probably should be a minimum move size too
                $lastError = $_
                $currentSize = $Size + (($maxSize - $successful)/2)             
            }
        }
    
        # If we weren't successful, throw the last error
        if(!$successful)
        {
            throw $lastError
        }
    }
    

    Here is an example of using the function:

    Resize-PartitionDynamic -diskNumber 2 -PartitionNumber 3 -Size 456GB