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?
Here is an overview of what you need to do:
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