Skip to content

Instantly share code, notes, and snippets.

@techdecline
Created October 22, 2021 08:23
Show Gist options
  • Select an option

  • Save techdecline/5a7c342526f70e31da24b62e0c390cce to your computer and use it in GitHub Desktop.

Select an option

Save techdecline/5a7c342526f70e31da24b62e0c390cce to your computer and use it in GitHub Desktop.
[cmdletbinding()]
param (
# vCenter Name
[Parameter(Mandatory)]
[ValidateScript({Test-NetConnection -ComputerName $_ -Port 443})]
[string]
$vCenterName,
# vCenter Credentials
[Parameter(Mandatory)]
[pscredential]
$Credential,
# VM Name Filter
[Parameter(Mandatory=$false)]
[string]
$VMNameFilter = "^ff2-(bo|ab).*",
# New Disk Size
[Parameter(Mandatory)]
[ValidateRange(64,256)]
[int]$NewSizeGB,
# Log File Path
[Parameter(Mandatory=$false)]
[String]$LogFilePath = $env:TEMP
)
begin {
try {
Import-Module VMware.PowerCLI -errorAction Stop
Import-Module LogStream
}
catch [System.Management.Automation.ActionPreferenceStopException] {
Write-Error "Go fix your PowerCLI Installation: $($error[0].Exception.Message)"
}
$logFile = Join-Path $LogFilePath -ChildPath "Extend-VMDisk_$(Get-Date -Format yyyyMMdd).log"
Start-Log -LogFilePath $logFile
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -ParticipateInCeip $false -confirm:$false
$null = Connect-VIServer -Server $vCenterName -credential $Credential
Write-VerboseLog -LogFilePath $logFile -Message "Connected VCenter $vCenterName with Credentials $($cred.UserName)"
}
process{
$vmArr = Get-VM | Where-Object {$_.Name -match $VMNameFilter -and $_.GuestId -match "^Windows.*"}
Write-VerboseLog -LogFilePath $logFile -Message "Found $($vmArr.Length) matching Virtual Machines"
$vmArr | ForEach-Object {
$tmpVm = $_
Write-VerboseLog -LogFilePath $logFile -Message "Processing Virtual Machine: $($tmpVm.Name)"
$primaryDisk = ($_ | Get-HardDisk)[0]
Write-VerboseLog -LogFilePath $logFile -Message "Current Primary Disk Size: $($primaryDisk.CapacityGB)"
if ($primaryDisk.CapacityGB -ge $NewSizeGB) {
Write-WarningLog -LogFilePath $logFile -Message "Current Disk Size already greater or equal...skipping"
}
else {
try {
Write-VerboseLog -LogFilePath $logFile -Message "Increasing Disk Size for Virtual Machine"
$primaryDisk | Set-HardDisk -Confirm:$false -CapacityGB $NewSizeGB
Write-VerboseLog -LogFilePath $logFile -Message "Increasing Disk Size in Operating System"
invoke-command -ComputerName $tmpVm.Name -scriptBlock {
$maxSize = (Get-PartitionSupportedSize -DriveLetter C).Sizemax
Resize-Partition -DriveLetter C -Size $maxSize
}
Write-VerboseLog -LogFilePath $logFile -Message "Successfully updated Virtual Machine"
}
catch {
write-ErrorLog -LogFilePath $logFile -Message "Could not increase Disk Size: $($error[0].exception.Message)"
}
}
}
}
end {
Stop-Log -LogFilePath $logFile
Disconnect-VIServer -Server $vCenterName -confirm:$false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment