First Technical Post

Well I’ve been a busy engineer this week and my time at the computer at home has been limited, Im still cracking on with the Docker course I bought from Udemy, more on that as I get further in, but I am also working on tidying up some build scripts I have for virtual machine builds, partially updating them and moving them to work on the MacBook Pro I now call home.

So the create VM script has always taken a datastore provided to it as a parameter, Ive always wanted to add functionality do that the script would take either a given datastore or it would find the Datastore with the most space on it and use that, so this morning to get the Powershell juices flowing I wrote a quick function to do that very thing.

Here it is

function Get-leastUtilizedDatastore {
param (
#Name of vCenter to Connect too
[Parameter(Mandatory = $true)]
[Parameter(mandatory = $false)]
#Gets Creds to use for the vCenter Connection
$creds = Get-Credential -Message “Enter Credentials to be used to connect to Vcenter $VIserver”
#Connect using those credentials
Connect-VIServer -Server $VIServer -Credential $creds | Out-Null
#Get all the Datastores attached to that vCenter or the host specified
if($host -ne $null){
$datastores = Get-Datastore -VMHost $RequiredHost
$datastores = Get-Datastore

#Cycle through the Datastores to get the one with most free space
foreach($store in $datastores){
if($store.FreeSpaceGB -gt $leastUtilisedDatastore.FreeSpaceGB){
$leastUtilisedDatastore = $store
#Disconnect from the VIServer for tidiness
Disconnect-VIServer -Server $VIServer -Force -Confirm:$false
#Return that value
return $leastUtilisedDatastore

This is the barebones script that I wrote, Ive modified it slightly to run on my home lab so that it just uses the Datastore on the SAN unit, but adding a filter or two using where-object, using the naming convention of my datastore, local stores have the host name in from of it (hostname_data_#) and the SAN has the Company name as its designation (Companyname_#) , I also wanted to exclude my VMware Content Library Drive too(CompanyNameContent), anyway here’s the code

$datastores = Get-Datastore | Where-Object {($_.Name -like “Companyname*”) -and ($ -ne “CompanyNameContent”)}

So this brings back all datastores that have the company name as the prefix of its name, but not my content library. This Function can then be added into the build script to take care of vm placement, or at least part of it

Leave a Reply

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