Alarm Triggered VCenter 5.5 Powershell Script

Here is what I am working on for deployment notification, this is just the basics and will expanded to report to a CMDB, add info to Ansible, send out emails, or whatever.

The following bat file is attached to an alarm trigger in VCenter, in this case the alarm triggered by creating a virtual machine:

	@echo off
	powershell -ExecutionPolicy Bypass -File "%~dpn0.ps1"

The bat file needs to be named EXACTLY the same as the ps1 file.

	Add-PSSnapin VMware.VimAutomation.Core
	if ($DefaultVIServers.Count -lt 1) {
		Connect-VIServer "VIServerName" -User username -Password Password
	$VM = (get-childitem Env:VMWARE_ALARM_TARGET_NAME).Value
	$VMID = (get-childitem Env:VMWARE_ALARM_TARGET_ID).Value
	$EventDesc = (get-childitem Env:VMWARE_ALARM_EVENTDESCRIPTION).Value

	$report = @()
	Get-VM -name "$VM"| Get-View | %{
	  $row = "" | select Name, Datastore, Path
	  $row.Name = $_.Name
	  $row.Datastore = (Get-View $_.Datastore[0]).Summary.Name
	  $current = Get-View $_.Parent
	  $path = $_.Name
	  do {
		$parent = $current
		 if($parent.Name -ne "vm"){$path =  $parent.Name + "\" + $path}
		 $current = Get-View $current.Parent
	  } while ($current.Parent -ne $null)
	  $row.Path = $path
	  $report += $row
	$report | out-file c:\variables.txt

This will report the VMName, the Path and the Datastore it resides on. With some tweaks you can pull data from VIX and get the Hostname IP address and all sorts of other goodies.

Jeremy Tirrell

Read more posts by this author.