Skip to content

Instantly share code, notes, and snippets.

@peterhynes
Created September 28, 2018 10:31
Show Gist options
  • Select an option

  • Save peterhynes/3dcc1fb489ecbfbadc5bd03b0e16c2c1 to your computer and use it in GitHub Desktop.

Select an option

Save peterhynes/3dcc1fb489ecbfbadc5bd03b0e16c2c1 to your computer and use it in GitHub Desktop.
#Script to add disk to VMs by Peter Hynes
#Version 1.0
#Created on the 27\09\2018
#Connect to the vCenter or vcenters and Run within PowerCLI
#You will need to create a txt file called vms.txt and place it in the same folder as this script. Put the list of VMs you are working with in this txt file.
$vcenter = Read-Host "Enter name of the vcenter you are working in"
#Connect to vcenter
connect-viserver $vcenter
#Prompt for new disk size
$diskSize = Read-Host "Enter the size of the disk you want to add"
#Create list of VMs from vms.txt file
$vms = get-content .\vms.txt
#List datastore cluster
Write-Host "Listing DataStoreClusters your VMs are on" -foregroundcolor Green
get-vm $vms | Get-DatastoreCluster | select name, @{N="Percentage Free Space(%)";E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}}
#loop through list of vms, check for space on datastorecluster and add disk if availible space is greater then 20%
foreach($vm in $vms){
$overProvisioned = get-vm $vms | Get-DatastoreCluster | select name, @{N="Percentage Free Space(%)";E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}} | where {$_."Percentage Free Space(%)" -le 10}
$dsc = get-vm $vm | Get-DatastoreCluster | select -ExpandProperty name
if($overProvisioned) {
Write-Host "DataStoreCluster $dsc has capacity less than 10%...Disk cannot be added to $vm" -foregroundcolor Yellow
$vm | Out-File -FilePath .\diskNotAddedList.txt -Append
}
else{
Write-Host "Adding disk for $vm" -foregroundcolor Green
New-HardDisk -vm $vm -CapacityGB $diskSize -Persistence persistent -StorageFormat Thin -confirm:$false -ErrorAction SilentlyContinue -ErrorVariable AddError | Out-Null
if ($AddError) {
Write-host "failed to add disk to $vm..check manually..." -foregroundcolor Yellow
$vm | Out-File -FilePath .\diskNotAddedList.txt -Append
}
else{
Write-Host "$diskSize GB disk added to $vm" -foregroundcolor Green
}
}
}
Disconnect-VIServer -Server $defaultVIServers -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Script complete" -foregroundcolor Green
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment