Tag Archives: PowerCLI

VI Toolkit 1.5 Getting Started and Undocumented Functions

0. Installing
Installing or upgrading the VI Toolkit 1.5 is as easy as Next, Next, Finish. And using the new VI Toolkit shortcut on your desktop allows quick and easy access to the Toolkit. But what about running these cmdlets from your scripts or integrating it with other snapins? Read on!

1. Setting up your profile
The new desktop shortcut does two things for you: it starts powershell with the VI Toolkit snapin loaded and it runs a script which modified the look of the Powershell window ánd adds some cool extra functions. If you want to have the same functionality in your normal Powershell window and your scripts, you have to copy some stuff to your Powershell profile. First, set up your profile:

a. Start a normal Powershell window.
b. Run the following command: Test-Path $profile
c. Did it return True? Then you already have a profile file. Did it return False, do step d.
d. Create a profile file by running: New-Item $profile -ItemType File

2. Adding the snap-in
a. Open your profile by running: Invoke-Item $profile
b. Add the following line to the profile file to load the snap-in: Add-PSSnapIn VMware.VimAutomation.Core -ErrorAction SilentlyContinue

3. Adding undocumented functions
a. Open the file C:\Program Files\VMware\Infrastructure\VIToolkitForWindows\Scripts\Initialize-VIToolkitEnvironment.ps1
b. Copy the following Function Blocks to your profile file: Get-VICommand, New-DatastoreDrive, New-VIInventoryDrive, Get-VIToolkitDocumentation, Get-VIToolkitCommunity

4. Undocumented Functions?
Ok, you can read about them in the Administrator’s Guide (http://www.vmware.com/support/developer/windowstoolkit/wintk10/doc/viwin_admin.pdf), but you might overlook these functions because they are not cmdlets, so Get-Command won’t show them (nor will Auto-Complete work for them).
Here’s a short description of each of them:

  • Get-VICommand: Displays all VI Toolkit cmdlets (equal to: Get-Command -PSSnapIn VMware.VimAutomation.Core);
  • New-DatastoreDrive: Allows you to browse a datastore like a drive (Example Usage: New-DatastoreDrive -Name <DriveName> -Datastore (Get-Datastore <DatastoreName>); Then jump to the drive: cd <DriveName>: );
  • New-VIInventoryDrive: Allows you to browse your Virtual Infrastructure like a drive (Example Usage: New-VIInventoryDrive -Name <DriveName> -Location (Get-Inventory <Folder-/Cluster-/ResourcePool-/HostName>); Then jump to drive: cd <DriveName>: );
  • Get-VIToolkitDocumentation: Opens the VI Toolkit Command Reference Help File;
  • Get-VIToolkitCommunity: Opens the VI Toolkit Community website.

More examples and scripts here soon!
Hugo

»crosslinked«

Check VMware Configuration with Powershell

I have promised you I would post this script, so here it is!

This Powershell script generates an overview of any items that are not available to every ESX server in a VMware cluster. These items might prevent your vm’s being vmotioned by DRS or restarted by HA. Pretty serious business, I’d say!

The items involved are:
1. datastores
2. LUNs (important when using Raw Device Mappings)
3. port groups

The output is a nicely formatted HTML page showing not only which items are misconfigured, but also where the are available and where they are absent.

Here’s an example:
Compare Screenshot

And here’s the script:
Compare-Clusters (Rename to .ps1)

Enjoy!
Hugo

Compare Cluster Datastores with Powershell

I showed you before how to compare the datastores for two ESX Servers using the VI Toolkit. But ideally, one would like to compare all ESX servers in a cluster to ensure VMotion and HA compatibility.
So I started scripting and it turns out to be pretty simple: only 4 lines of code in Powershell! It does the comparison for all your clusters and returns clean little tables with datastores you should investigate.

SCRIPT CODE:

ForEach ($Cluster in (Get-Cluster | Sort Name))
{
$VMHosts = Get-Cluster $Cluster.Name | Get-VMHost
$Datastores = $VMHosts | Get-Datastore
$VMHosts | ForEach {Compare-Object $Datastores ($_ | Get-Datastore)} | ForEach {$_.InputObject} | Sort Name | Select @{N=$Cluster.Name;E={$_.Name}} -Unique | Format-Table
}

SAMPLE OUTPUT:

TEST CLUSTER 1
——————
DATASTORE1
LOCAL01
LOCAL02
LOCAL03

TEST CLUSTER 2
——————
DATASTORE2
DATASTORE3
LOCAL06
LOCAL07
LOCAL08
LOCAL09

Coming very soon: a full-blown script that compares datastores, LUNs and portgroups across your clusters ánd identifies exactly where the differences are! Stay tuned…

Another way to gather VMware disk info with Powershell

I’ve created another way to gather and display VMware Virtual Disk information with the Powershell VI Toolkit.

The attached script generates a csv-file with all Virtual Machines’ Disks, in which Datastore they are stored, the LUN IDs of the extents that make up this Datastore (in HEX) and the Vendor of the SAN those LUNs are on (just in case you have multiple). Simpy a great way to determine which LUNs are used by which virtual server(s) in a complex environment.

diskinfo

By the way: the script is filled with comments to allow you to learn how it works.

create-vmdiskoverview (Rename to .ps1)

Enjoy!

Hugo

Compare ESX configurations with Powershell

One of the challenges in managing a large VMware Infrastructure is keeping all ESX Servers within a cluster equal. This is essential for having vmotion capabilities and therefore essential for a solid HA configuration. I have showed you earlier how to add the LUN Count for each ESX Server to your VI Client. This allows you to spot differences quickly. But finding exactly which datastores are missing on which ESX Server can be a bigger challenge.

Here are some small functions that can help you determine where the major differences are.

Comparing datastores:

function Compare-VMHostDatastores
{
param([string]$host1,[string]$host2)
$a = Get-VMHost $host1 | Get-Datastore | %{$_.Name}
$b = Get-VMHost $host2 | Get-Datastore | %{$_.Name}
Compare-Object $a $b
}

Compare-VMHostDatastores esxServer1 esxServer2

InputObject                         SideIndicator
———–                                ————-
esxServer1_Local             <=
esxServer2_Local             =>
DATASTORE_TEST1         =>

And comparing Port Groups:

function Compare-VMHostPortgroups
{
param([string]$host1,[string]$host2)
$a = Get-VirtualPortGroup (Get-VMHost $host1) | %{$_.Name}
$b = Get-VirtualPortGroup (Get-VMHost $host2) | %{$_.Name}
Compare-Object $a $b
}

Compare-VMHostPortgroups esxServer1 esxServer2

InputObject                SideIndicator
———–                      ————-
PortGroup_TEST     <=
Internal                       <=

Maybe you prefer to go the other way around and check to which ESX servers a specific datastore is attached?

function Get-DatastoreHosts
{
param([string]$datastore)
Get-VMHost -Datastore (Get-Datastore $datastore) | Sort Name | %{$_.Name}
}

PS D:Scripts> Get-DatastoreHosts DATASTORE_TEST1

esxServer2
esxServer3

Thank Microsoft for Powershell and the Compare-Object cmdlet!

Hugo

Getting detailed VMware license information with Powershell

I have showed you before how to access the License Manager with the Powershell VMware VI Toolkit. But the properties of the License Manager appear to only reflect the Virtual Center License Information. So how do we get information about licensing for each individual ESX Server?
We need to take a look at the methods of the License Manager.
First, we connect to the License Manager:

$SI = Get-View ServiceInstance
$LM = Get-View $SI.Content.LicenseManager

Examine the methods of the License Manager:

$LM | Get-Member -MemberType method
methods

Lets see how the QueryLicenseUsage method works:

$LM.QueryLicenseUsage
methoddef

It requires one parameter host of type ManagedObjectReference. So we need a reference to a VMHost:

$VMHostView = Get-VMHost “NAME” | Get-View

$VMHostRef = $VMHostView.MoRef

Now we can call the method:

$LicUse = $LM.QueryLicenseUsage($VMHostRef)

Useful information includes:

$LicUse.Source.LicenseServer   # Contains the license server name and port

$LicUse.ReservationInfo   # Contains license information for each feature available
reservationinfo

To find more information about each feature, take a look at the FeatureInfo property of the License Manager:

$LM.FeatureInfo

featureinfo

Now, you can take the info you need and use it in your scripts.

Enjoy!

Hugo

Add RDM Size info to VI Client using Powershell

I have had a lot of comments on my sample scripts that add information to the VI Client using Custom Fields. I did have to resolve some issues with the scripts, so I have updated the scripts in the original post here. Be sure to refresh your browser to get the latest versions.

In the VMware VI Toolkit Communities, a request was made for a similar script that adds the total size of all Raw Device Mappings (RDMs) on a VM to a Custom Field in the VI Client. The difference between this sample script and the ones I showed you earlier, is that the information is now pulled from $VM and not from $VMView. So I pulled the Get-View command inside the loop and here’s the result:

add-vmrdmsize (rename to .ps1)

Let me know if you can’t get it to work.

Hugo

Add Custom Fields to VI Client with Powershell (Samples)

In my previous post, I showed you how to add information to your VI Client using Custom Fields. Here are some ready-to-go scripts to add very useful info:

Snapshot Count

I already showed you how to do this, but I have now added an IF-statement so that only changes are updated (equal values are not overwritten). And I have added Julian Wood’s correction. add-vmsnapshotcount (rename to .ps1)

Total Snapshot Size

The number of snapshots is quite inetresting, but even more interesting, is the total size of the delta files all snapshots are occupying. They might be eating up all your precious SAN space. Plus, reverting to or committing a large snapshot is tricky. add-vmsnapshotsize1 (rename to .ps1)

Host Hardware Model

Want to see what models of hardware you are using in your datacenter? You could look at the summary tab of each host. Or run this script to add the info to the every Hosts tab in the VI Client. Select your Datacenter, select the Hosts tab and enjoy! add-vmhostmodel (rename to .ps1)

Host ESX Version

Did you update all your ESX Servers to the latest version? Check it quickly using this script. add-vmhostversion (rename to .ps1)

Host LUN Count

Last but certainly not least: are you sure every datastore you are using is available to all your ESX Servers? It is visible at a glance when you add the LUN Count to your VI Client! add-vmhostluncount (rename to .ps1)

Happy Holidays!

Hugo

Add Snapshot Information to the VI Client using Powershell

Although I spend quite some time in the Powershell Command Line Interface, the main tool for managing the Virtual Infrastructure remains the VI Client. So wouldn’t it be great if we could somehow show the results of our Powershell VI Toolkit scripts inside the VI Client?
Well, we can! Let’s take a closer look at Custom Fields / Custom Attributes.
If you select either a VMHost (ESX Server) or a VM in the VI Client and open the Summary tab, you will see the Annotations section in the bottom left. When you click Edit, I’m sure you have used the Notes section to enter Descriptions. But have you ever used the Attributes section? Here you can manually add and remove custom attributes and their values. Go ahead and create one. Then select a cluster or datacenter and click the Hosts or Virtual Machines tab. You will notice you can display your custom attribute in this table view, just like all the other properties of your VMs / Hosts. Pretty sweet!
But we don’t want to add and update those fields manually, now do we? Of course not, we’ve got Powershell! Let’s see how we can automate this.
We start by connecting to the Custom Fields Manager:

$VCServerName = “MYVCSERVER”
$VC = Connect-VIServer $VCServerName
$SI = Get-View ServiceInstance
$CFM = Get-View $SI.Content.CustomFieldsManager

Take a look at the $CFM.Field property. It contains an array of available fields. Next step: add our own custom field.

# Variables
$CustomFieldName = “Snapshots”
$ManagedObjectType = “VirtualMachine”
# Check if the custom field already exists
$myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName}
If (!$myCustomField)
{
# Create Custom Field
$FieldCopy = $CFM.Field[0]
$CFM.AddCustomFieldDef($CustomFieldName, $ManagedObjectType, $FieldCopy.FieldDefPrivileges, $FieldCopy.FieldInstancePrivileges)
}

Final step: Fill the custom field with some relevant information:

# Fill Custom Fields
$VMs = Get-VM
$VMViews = $VMs | Get-View
ForEach ($VMView in $VMViews)
{
$SnapshotCount = ($VMView.Snapshot.RootSnapshotList | Measure-Object).Count
If ($SnapShotCount)
{
$VMView.setCustomValue($CustomFieldName,$SnapShotCount)
}
}

Now take a look at the VI Client:
snapshots
More examples coming soon!
Hugo

PS: Don’t forget to schedule the script to run at an interval, so the values are kept up-to-date!

Get VMware Disk Usage with Powershell

Using VMware seriously requires a lot of (shared) storage. This kind of storage (on a SAN for instance) is quite expensive. So you might want to check if you are wasting a lot of this space. When you look at the storage in VMware, it consists of multiple abstraction layers. A virtual machine has one or more Logical Disks, which are indicated by driveletters. You can use WMI to determine the amount of used and free space (Win32_LogicalDisk). One or more logical disks are contained in a partition. One or more partitions reside on a physical disk. That physical disk is really a virtual disk, a vmdk file to be precise. One or more vmdk files reside in a Datastore, which can be found on a LUN on your SAN.
The following script enumerates most of these layers (from logical disk to datastore) and calculates the used and free space. The final line exports the results to a csv file for use in Excel. And the script also helps you to calculate the average free space by showing the totals without the duplicates (don’t try to average the averages in excel, that’s not accurate because datastores contain duplicates and averages should be weighed).

UPDATE: I have modified the script, so no more matching of disks is done based on disk size. The match is made based on SCSI IDs and WMI relations. Thanks to adavidm on the VI Toolkit Community Continue reading