Add Vmx Path to VI Client using Powershell
The following script is a request from David Gontie, who was kind enough to comment on a previous post.
He’d like to add the location of his vm’s to a custom field. This is especially handy if you store all the files for a vm in a single datastore.
Here you go David:
##############################
# Script created by Hugo Peeters #
# https://www.peetersonline.nl #
##############################
# Variables
$VCServerName = "MYVCSERVER"
$CustomFieldName = "VMX"
$ManagedObjectType = "VirtualMachine"
# Script
$VC = Connect-VIServer $VCServerName
$SI = Get-View ServiceInstance
$CFM = Get-View $SI.Content.CustomFieldsManager
$myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName}
If (!$myCustomField)
{
# Create Custom Field
$FieldCopy = $CFM.Field[0]
$CFM.AddCustomFieldDef($CustomFieldName,$ManagedObjectType,$FieldCopy.FieldDefPrivileges,$FieldCopy.FieldInstancePrivileges)
$myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName}
}
# Fill Custom Fields
$VMs = Get-VM
ForEach ($VM in $VMs)
{
$VMView = $VM | Get-View
$VMXPath = $VMView.Config.Files.VMPathName
# Compare value to current value
If ($VMXPath -ne ($VMView.CustomValue | ?{$_.Key -eq $myCustomField.Key}).Value)
{
# Set Custom Value
$VMView.setCustomValue($CustomFieldName,$VMXPath)
}
Clear-Variable VMXPath -ErrorAction SilentlyContinue
Clear-Variable VMView -ErrorAction SilentlyContinue
}
Disconnect-VIServer -Confirm:$False
Enjoy!
Hugo
