Mass Custom Attribute Writes with PowerCLI

In my previous article I mentioned that how can you handle Custom Attributes. I would like to provide you an example script, witch read attributes from a CSV file, and insert it to vCenter Server line by line.


Here is my script, all part commented.

#inport data from CSV
$InputData = Import-Csv ./Resources.csv -Delimiter ';'
#count row numbers
$InputDataRows = $InputData.length - 1
#inform a user about the fetched rows
Write-Host "The csv Rows are $InputDataRows"
#this loop goes line by line
$counter = -1
While ($counter -lt $InputDataRows)
{
$counter += 1
#prepare error handling
$Error.Clear()
#inform the user about the VM
Write-Host $InputData[$counter].VMname
#put a VM into the $vm variable
$vm = Get-VM -name $InputData[$counter].VMname
if ($Error.Count -ne 0)
{
#if the VM not exist on the vCenter Server
Write-Host "Error, no VM"
}
Else
{
#if the VM exist on the vCenter Server
#variables from CSV
$HostID = $InputData[$counter].hostid
$SAPnumber = $InputData[$counter].SAPnumber
$Owner = $InputData[$counter].Owner
#for debugging or verbose mode you should uncomment
#the following lines
#Write-Host "HostID = $HostID"
#Write-Host "SAPnumber = $SAPnumber"
#Write-Host "Owner = $Owner"
#Write-Host ""
#set the Custom Attributes
$vm |Set-CustomField -name HostID -Value $HostID
$vm |Set-CustomField -name SAPnumber -Value $SAPnumber
$vm |Set-CustomField -name Owner -Value $Owner
}
}

That’s all!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s