Home > Blogs > VMware PowerCLI Blog > Monthly Archives: March 2012

Monthly Archives: March 2012

Working with vCloud Metadata in PowerCLI

AlanFeb2012_thumb_thumb1_thumb_thumb[2]
Posted by
Alan Renouf
Technical Marketing

Yesterday William Lam created a great post which showed us how easy it was to work with vCloud Director (vCD) Metadata, he outlined how easy it was to add/update and remove metadata from the various objects which supported this function in vCD.

As he explained, we can use this to assign various useful information to our vCD objects, one of these was the contact information.  In this post I will show example scripts and how the code would look in PowerCLI when working with vCD Metadata.

In our example we will have a list of VMs starting with VMAlpha, these will be owned by Bob and will need to be marked in vCD with Bob as the owner, firstly lets list the VMs in PowerCLI:

SNAGHTML3c481d5c

Once we have listed these we can easily import the code from the scripts section below to give us three new PowerShell advanced functions which allow us to work with metadata. With these imported we can easily add new metadata to our VM objects, each piece of metadata has to have a unique key and a value, in this case the key will be “Owner” and the value will be Bob’s email address which is “Bob@corp.local”.

SNAGHTML3c4b7145

With this information added to these objects it is easy to list all VMs and any metadata which may exist on these objects, lets now list all our VMs and the metadata which belongs to them:

SNAGHTML3c4fa2e0

Or just the contact information:

SNAGHTML3c50c905

And of course we can very easily remove these items with the Remove-CIMetadata advanced function:

SNAGHTML3c534508

Metadata can be very useful for keeping data with the objects as they move around, and remember its not just VMs which can hold metadata, the following objects can be used with these functions:

Tenant (User) Provider (Admin)
Catalog
CatalogItem CatalogItem
Media Media
Network
Organization
Organization vDC
Provider vDC
vApp vApp
vAppTemplate vAppTemplate
Virtual Machine (treated as a vApp) Virtual Machine (treated as a vApp)

 

Metadata Functions

Paste and run the following functions into your window to allow you to perform the actions explained above.

Function New-CIMetaData {
    <#
    .SYNOPSIS
        Creates a Metadata Key/Value pair.
    .DESCRIPTION
        Creates a custom Metadata Key/Value pair on a specified vCloud object
    .PARAMETER  Key
        The name of the Metadata to be applied.
    .PARAMETER  Value
        The value of the Metadata to be applied.
    .PARAMETER  CIObject
        The object on which to apply the Metadata.
    .EXAMPLE
        PS C:\> New-CIMetadata -Key "Owner" -Value "Alan Renouf" -CIObject (Get-Org Org1)
    #>
     [CmdletBinding(
         SupportsShouldProcess=$true,
        ConfirmImpact="High"
    )]
    param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [PSObject[]]$CIObject,
            $Key,
            $Value
        )
    Process {
        Foreach ($Object in $CIObject) {
            $Metadata = New-Object VMware.VimAutomation.Cloud.Views.Metadata
            $Metadata.MetadataEntry = New-Object VMware.VimAutomation.Cloud.Views.MetadataEntry
            $Metadata.MetadataEntry[0].Key = $Key
            $Metadata.MetadataEntry[0].Value = $Value
            $Object.ExtensionData.CreateMetadata($Metadata)
            ($Object.ExtensionData.GetMetadata()).MetadataEntry | Where {$_.Key -eq $key } | Select @{N="CIObject";E={$Object.Name}}, Key, Value
        }
    }
}
Function Get-CIMetaData {
    <#
    .SYNOPSIS
        Retrieves all Metadata Key/Value pairs.
    .DESCRIPTION
        Retrieves all custom Metadata Key/Value pairs on a specified vCloud object
    .PARAMETER  CIObject
        The object on which to retrieve the Metadata.
    .PARAMETER  Key
        The key to retrieve.
    .EXAMPLE
        PS C:\> Get-CIMetadata -CIObject (Get-Org Org1)
    #>
    param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [PSObject[]]$CIObject,
            $Key
        )
    Process {
        Foreach ($Object in $CIObject) {
            If ($Key) {
                ($Object.ExtensionData.GetMetadata()).MetadataEntry | Where {$_.Key -eq $key } | Select @{N="CIObject";E={$Object.Name}}, Key, Value
            } Else {
                ($Object.ExtensionData.GetMetadata()).MetadataEntry | Select @{N="CIObject";E={$Object.Name}}, Key, Value
            }
        }
    }
}
Function Remove-CIMetaData {
    <#
    .SYNOPSIS
        Removes a Metadata Key/Value pair.
    .DESCRIPTION
        Removes a custom Metadata Key/Value pair on a specified vCloud object
    .PARAMETER  Key
        The name of the Metadata to be removed.
    .PARAMETER  CIObject
        The object on which to remove the Metadata.
    .EXAMPLE
        PS C:\> Remove-CIMetaData -CIObject (Get-Org Org1) -Key "Owner"
    #>
     [CmdletBinding(
         SupportsShouldProcess=$true,
        ConfirmImpact="High"
    )]
    param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [PSObject[]]$CIObject,
            $Key
        )
    Process {
        $CIObject | Foreach {
            $metadataValue = ($_.ExtensionData.GetMetadata()).GetMetaDataValue($Key)
            If($metadataValue) { $metadataValue.Delete() }
        }
    }
}

Note: In between writing these functions and posting this article I noticed that Clinton Kitson has also released some similar functions,  make sure you check out his functions and examples here.

Get notification of new blog postings and more by following VMware PowerCLI on Twitter: @PowerCLI

Automating the creation of vCD Provider VDCs

AlanFeb2012_thumb_thumb1_thumb_thumb[1]
Posted by
Alan Renouf
Technical Marketing

Following my previous post where I showed how easy and quick it was to create Organizations, Users and Organization VDC’s I thought it would be good to take it one step further or in this case backwards, to create the items we created in the last post we must first need a Provider VDC, we need this to provide the resources to the Organization VDC.

The script detailed further in this post can be used to create a Provider VDC, to do this we will obviously need to provide resources from a vCenter, for this to be done we need to connect to both the Cloud Infrastructure and the vSphere Infrastructure which is not an issue for PowerCLI.

In the script I have assumed that all hosts in the cluster will have access to the same shared storage and that this is the storage which will be used in the Provider VDC, I have also assumed that we will be using a Cluster to back our Provider VDC and not a resource pool… Although technically this is the root resource pool anyway, to learn more about the root resource pool make sure you read William Lams great introductory posts to the API here.

Creating a Provider VDC

The following script can be used to create a Provider VDC, it is shown as an example and not a complete function which provides all parameters and functions needed in a more complex situation:

Function New-ProviderVDC {

    Param (
        $Cluster,
        $Description,
        [Switch]$Enabled,
        $HWVersion
    )
   
    Process {

        $vcloud = $DefaultCIServers[0].ExtensionData
        $admin = $vcloud.GetAdmin()
        $ext = $admin.GetExtension()
        $ProvidervDCDetails = New-Object VMware.VimAutomation.Cloud.Views.VMWProviderVdc
        $ProvidervDCDetails.Name = $Cluster
        $VC = $ext.GetVimServerReferences()
        $VimServer = $vc.VimServerReference[0]
        $ProvidervDCDetails.VimServer = $VimServer
        $ProvidervDCDetails.Description =$Description
        $ProvidervDCDetails.IsEnabled = $Enabled
        $Datastorerefs = New-Object VMware.VimAutomation.Cloud.Views.VimObjectRefs
        $Datastores = @()
        Foreach ($DS in (Get-Cluster $Cluster | Get-VMHost | Select -First 1 | Get-Datastore | Where {$_.Extensiondata.Summary.MultipleHostAccess})) {
            $Datastore = New-Object VMware.VimAutomation.Cloud.Views.VimObjectRef
            $Datastore.VimServerRef = $VimServer
            $Datastore.MoRef = (($DS).Id).Trim("Datastore-")
            $Datastore.VimObjectType = "DATASTORE"
            $Datastores += $Datastore
        }
        $Datastorerefs.VimObjectRef = $Datastores
        $ProvidervDCDetails.DataStoreRefs = $Datastorerefs
        $RPrefs = New-Object VMware.VimAutomation.Cloud.Views.VimObjectRefs
        $RPrefs.VimObjectRef = @(New-Object VMware.VimAutomation.Cloud.Views.VimObjectRef)
        $RPrefs.VimObjectRef[0].VimServerRef = $VimServer
        $RPrefs.VimObjectRef[0].MoRef = ((Get-Cluster $Cluster | Get-ResourcePool Resources).ExtensionData).Moref.Value
        $RPrefs.VimObjectRef[0].VimObjectType = "RESOURCE_POOL"
        $ProvidervDCDetails.ResourcePoolRefs = $RPrefs
        #If HWVersion is not defined then use 7 by default
        If ($HWVersion) {
            $HWVer = "vmx-0$($HWVersion)"
        } Else {
            $HWVer = "vmx-07"
        }
        $ProvidervDCDetails.HighestSupportedHardwareVersion = $HWVer

        $ext.CreateProvidervdc($ProvidervDCDetails)
    }
}

Running the script

As mentioned before, we must fist connect to both the Cloud Infrastructure as well as the Virtual Infrastructure, once this has been done we can use the above function to create our provider VDC by passing it the cluster information and the hardware version:

# Adding PowerCLI vCD snapin
if (!(get-pssnapin -name VMware.VimAutomation.Cloud -erroraction silentlycontinue)) {
    add-pssnapin VMware.VimAutomation.Cloud
}

# Adding PowerCLI snapin
if (!(get-pssnapin -name VMware.VimAutomation.Core -erroraction silentlycontinue)) {
    add-pssnapin VMware.VimAutomation.Core
}

# Connectiong to CI and VI
Connect-VIServer myvc -User Administrator -Password vmware
Connect-CIServer myvcd -User Administrator –Password P@ssw0rd

# Create the Provider VDC
New-ProviderVDC -Cluster Cluster01 -Description "A Description for my cluster" -Enabled -HWVersion 7

The Result

A shiny new Provider VDC

DataStoreRefs                   : VMware.VimAutomation.Cloud.Views.VimObjectRefs
ResourcePoolRefs                : VMware.VimAutomation.Cloud.Views.VimObjectRefs
VimServer                       : {VC01}
HostReferences                  : VMware.VimAutomation.Cloud.Views.VMWHostReferences
HighestSupportedHardwareVersion : vmx-07
Status                          : 0
ComputeCapacity                 : VMware.VimAutomation.Cloud.Views.RootComputeCapacity
StorageCapacity                 : VMware.VimAutomation.Cloud.Views.ProviderVdcCapacity
AvailableNetworks               : VMware.VimAutomation.Cloud.Views.AvailableNetworks
Capabilities                    :
Vdcs                            :
IsEnabled                       : True
NetworkPoolReferences           : VMware.VimAutomation.Cloud.Views.NetworkPoolReferences
Name                            : Cluster01
Id                              : urn:vcloud:providervdc:b2746976-c674-45bc-89b1-c6c38bad42f7
Description                     : A Description for my cluster
Tasks                           : VMware.VimAutomation.Cloud.Views.TasksInProgress
Client                          : VMware.VimAutomation.Cloud.Views.CloudClient
Href                            :
https://labvcd/api/admin/extension/providervdc/b2746976-c674-45bc-89b1-c6c38bad42f7
Type                            : application/vnd.vmware.admin.vmwprovidervdc+xml
Link                            : {, , , …}
AnyAttr                         : {xsi:schemaLocation}
VCloudExtension                 :

Or as can be seen from the GUI:

image

Of course the more attentive of you will notice the system alerts on the status, this is because we now need to prepare the hosts in this Provider VDC but that’s a subject for another blog post !

Get notification of new blog postings and more by following VMware PowerCLI on Twitter: @PowerCLI

Automating creation of vCD Organizations, Users and Org vDCs

AlanFeb2012_thumb_thumb1_thumb_thumb
Posted by
Alan Renouf
Technical Marketing

In Part 1 of this blog series I wrote about how I presented together with a colleague of mine Vladimir Goranov at Partner Exchange 2012.  I already showed you the reporting script and demonstration on how to create graphs straight from PowerCLI which detail the resources and statistics in your Cloud Infrastructure (CI).

Following the reporting side of the vCloud Director snap-in we explained that although in PowerCLI 5.0.1 the cmdlets were mainly “GET” cmdlets which retrieved data from the Cloud there was also a cmdlet called Get-CIView and a property on the returned objects called .ExtensionData.

The Get-CIView cmdlet and ExtensionData property exposes the entire vCloud Director API and allows us to make changes to the CI, this opens up multiple possibilities and moves us away from just retrieving data and allows us to create and alter our CI.

In our presentation we showed how the current cmdlets could be used to create some advanced functions which would look just like PowerShell cmdlets and could be used to create new Organizations, Users and Organizational vDC's.

We then used the scenario of a service provider having to add multiple new Organizations into their CI, would they add these one by one using the GUI ? Maybe they already have their own product which integrates into the vCloud Director APIs and they didn’t need to do this but for those looking for a free and easy way to create multiple Orgs we showed how easy it was to create 50 new orgs in less than 2 minutes.

Creating 50 new Organizations in less than 2 minutes

The below video was used in the presentation we gave at Partner Exchange, follow through to see the creation of a single Org, User and Org vDC and then how we can create 50 orgs in less than 2 minutes from an Excel spreadsheet:

The Scripts

Below are the scripts and examples we used in the presentation, please note these are not fully formed cmdlets and are shown as examples of how you can use the Get-CIView cmdlet and ExtensionData to create these CI objects, you may need to adjust these functions to perform extra tasks or to work in your CI.

Function New-Org {
    Param (
        $Name,
        $FullName,
        $Description,
        [Switch]$Enabled,
        [Switch]$PublishCatalogs
    )
    Process {
        $vcloud = $DefaultCIServers[0].ExtensionData
       
        $AdminOrg = New-Object VMware.VimAutomation.Cloud.Views.AdminOrg
        $adminOrg.Name = $name
        $adminOrg.FullName = $FullName
        $adminOrg.Description = $description
        $adminOrg.IsEnabled = $Enabled

        $orgSettings = New-Object VMware.VimAutomation.Cloud.Views.OrgSettings
        $orgGeneralSettings = New-Object VMware.VimAutomation.Cloud.Views.OrgGeneralSettings
        $orgGeneralSettings.CanPublishCatalogs = $PublishCatalogs
        $orgSettings.OrgGeneralSettings = $orgGeneralSettings

        $adminOrg.Settings = $orgSettings

        $org = $vcloud.CreateOrg($adminOrg)
        Get-Org -Name $name
    }
}

Function New-CIUser {
    Param (
        $Name,
        $Pasword,
        $FullName,
        [Switch]$Enabled,
        $Org,
        $Role
    )
    Process {
        $OrgED = (Get-Org $Org).ExtensionData
        $orgAdminUser = New-Object VMware.VimAutomation.Cloud.Views.User
        $orgAdminUser.Name = $Name
        $orgAdminUser.FullName = $FullName
        $orgAdminUser.Password = $Pasword
        $orgAdminUser.IsEnabled = $Enabled

        $vcloud = $DefaultCIServers[0].ExtensionData
       
        $orgAdminRole = $vcloud.RoleReferences.RoleReference | where {$_.Name -eq $Role}
        $orgAdminUser.Role = $orgAdminRole
       
        $user = $orgED.CreateUser($orgAdminUser)
        Get-CIUser -Org $Org -Name $Name
    }
}   

Function New-OrgVDC {
    Param (
        $Name,
        [Switch]$Enabled,
        $Org,
        $ProviderVDC,
        $AllocationModel,
        $CPULimit,
        $CPUAllocated,
        $MEMAllocated,
        $MEMLimit,
        $StoraqeLimit
    )
    Process {
        $adminVdc = New-Object VMware.VimAutomation.Cloud.Views.AdminVdc
        $adminVdc.Name = $name
        $adminVdc.IsEnabled = $Enabled
        $providerVdc = Get-ProviderVdc $ProviderVDC
        $providerVdcRef = New-Object VMware.VimAutomation.Cloud.Views.Reference
        $providerVdcRef.Href = $providerVdc.Href
        $adminVdc.ProviderVdcReference =$providerVdcRef
        $adminVdc.AllocationModel = $AllocationModel
        $adminVdc.ComputeCapacity = New-Object VMware.VimAutomation.Cloud.Views.ComputeCapacity
        $adminVdc.ComputeCapacity.Cpu = New-Object VMware.VimAutomation.Cloud.Views.CapacityWithUsage
        $adminVdc.ComputeCapacity.Cpu.Units = "MHz"
        $adminVdc.ComputeCapacity.Cpu.Limit = $CPULimit
        $adminVdc.ComputeCapacity.Cpu.Allocated = $CPUAllocated
        $adminVdc.ComputeCapacity.Memory = New-Object VMware.VimAutomation.Cloud.Views.CapacityWithUsage
        $adminVdc.ComputeCapacity.Memory.Units = "MB"
        $adminVdc.ComputeCapacity.Memory.Limit = $MEMLimit
        $adminVdc.ComputeCapacity.Memory.Allocated = $MEMAllocated
        $adminVdc.StorageCapacity = New-Object VMware.VimAutomation.Cloud.Views.CapacityWithUsage
        $adminVdc.StorageCapacity.Units = "MB"
        $adminVdc.StorageCapacity.Limit = $StorageLimit
       
        $OrgED = (Get-Org $Org).ExtensionData
        $orgVdc = $orgED.CreateVdc($adminVdc)
        Get-OrgVdc $name
    }
}

# Connect to our Cloud Infrastructure
Connect-CIServer vCloud

# Create a new Org
New-Org -Name "PowerCLIRocks" -FullName "PowerCLI Rocks hard!" -description "PowerCLI really rocks hard." -Enabled

# Create a new Administrator for that Org
New-CIUser -Enabled -Name "PowerCLIRocksAdmin" -FullName "PowerCLI Rocks Administrator"
    -Pasword "Pa$$w0rd" -Org "PowerCLIRocks" -Role "Organization Administrator"

# Create a new Org VDC for that Org
New-OrgVDC -Name "PowerCLIRocksVDC" -Org "PowerCLIRocks"-AllocationModel "AllocationPool" -Enabled

    -CPUAllocated 500 -CPULimit 1000 -MEMAllocated 1000 -MEMLimit 2000 -ProviderVDC "Bronze" -StorageLimit 1024

# Create all the Urgent Orgs
Import-Csv c:\UrgentWork\UrgentOrgs.csv | Foreach {
    New-Org -Name $_.OrgName -FullName $_.OrgFullName -description $_.OrgDesc -Enabled
}

Get notification of new blog postings and more by following VMware PowerCLI on Twitter: @PowerCLI

Reporting with the PowerCLI vCD Cmdlets

AlanFeb2012_thumb_thumb1_thumb_thumb
Posted by
Alan Renouf
Technical Marketing

Recently at Partner Exchange 2012 I presented with a colleague of mine Vladimir Goranov who is an R&D Manager at VMware and focuses on automation and PowerCLI.

Our presentation was entitled “vCloud Infrastructure Automation – powered by PowerCLI”.

In the presentation we took people through some basic reporting and then demonstrated how this could be taken one step further to produce some nice easy to view reports which included hooking into Excel and automatically creating a spreadsheet complete with several tabs and bar graphs.

After this we demonstrated how the current version of PowerCLI – Version 5.0.1 could be used to not only view information but also create more advanced scripts which would allow you to create Organizations, Organization VDCs and Users. This will be shown in part 2 of this blog series but for now lets stick to the reporting.

Advanced Reporting

With PowerShell being able to integrate into multiple applications a great way to automatically present your data is through Excel, this can be made even easier with a great function created by Luc Dekens called Export-XLS, with his advanced function we can export the data and create the graphs we need with a couple of lines of code.  An example of this can be seen in the screenshot below:

image

The Video

The below video was used in the presentation we gave at Partner Exchange, follow through to see both basic and Advanced Reporting:

 

The Script

As mentioned you will first of all need to add the Export-XLS function to your PowerCLI session which can be found on Luc’s site here.  After this change the output filename in the script below and your advanced reports will be created giving you nice graphs for each of your Organization vDCs resources and a sheet showing which of your users has created the most VMs.

$Filename = "c:\UrgentWork\CloudStats.xlsx"
Get-OrgVdc | Select Name,
    @{N="TotalCPUUsedGhz";E={[Math]::Round($_.CPUUsedGhz, 2)}},

    @{N="TotalCPULimitGhz";E={[Math]::Round($_.CPULimitGhz, 2)}}
    | Export-Xls -Path $Filename -WorksheetName "CPUUsage" -ChartType "xlColumnClustered" -AppendWorksheet:$false
Get-OrgVdc | Select Name,

    @{N="TotalMemUsedGB";E={[Math]::Round($_.MemoryUsedGB,2)}},
    @{N="TotalMemLimitGB";E={[Math]::Round($_.MemoryLimitGB, 2)}}

    | Export-Xls -Path $Filename -WorksheetName "MemoryUsage" -ChartType "xlColumnClustered"
Get-OrgVdc | Select Name,
    @{N="TotalStorageUsedGB";E={[Math]::Round($_.StorageUsedGB,2)}},

    @{N="TotalStorageLimitGB";E={[Math]::Round($_.StorageLimitGB,2)}}
    | Export-Xls -Path $Filename -WorksheetName "StorageUsage" -ChartType "xlColumnClustered"
Get-CIUser | Select Name,

    @{N="TotalDeployedVMs";E={$_.DeployVMCount}},
    @{N="TotalStoredVMs";E={$_.StoredVMCount}}

    | Export-Xls -Path $Filename -WorksheetName "User VM Counts" -ChartType "xlColumnClustered"

Invoke-Item $Filename

Here is the code for the other scripts which were used as part of the reporting section in the presentation and the above video demonstration:

#List all vApps in the Cloud Infrastructure
Get-CIVApp

#List all vApps owned by a particular user
Get-CIVApp -Owner MrUser01

# Find OrgVDCs which have potential sales for storage
Write-Host "OrgVDCs which have potential sales for storage"
Get-OrgVdc | Where { $_.AllocationModel -eq "AllocationPool" } | Select Name,
    @{N="StorageRemainingGBPerc";E={[Math]::Round((100-($_.StorageusedGB*100/$_.StorageLimitGB)),2)}}

    | Where { $_.StorageRemainingGBPerc -lt 30 }
   
# Find OrgVDCs which have potential sales for Memory
Write-Host "OrgVDCs which have potential sales for Memory"
Get-OrgVdc | Where { $_.AllocationModel -eq "AllocationPool" } | Select Name,
    @{N="MemRemainingGBPerc";E={[Math]::Round((100-($_.MemoryUsedGB*100/$_.MemoryLimitGB)),2)}}

    | Where { $_.MemRemainingGBPerc -lt 30 }
   
# Find OrgVDCs which have potential sales for CPU
Write-Host "OrgVDCs which have potential sales for CPU"
Get-OrgVdc | Where { $_.AllocationModel -eq "AllocationPool" } | Select Name,
    @{N="CpuRemainingGhzPerc";E={[Math]::Round((100-($_.CpuUsageGhz*100/$_.CpuLimitGhz)),2)}}

    | Where { $_.CpuRemainingGhzPerc -lt 30 }

In part two of this series of blog posts we will show how you can use the current PowerCLI 5.0.1 Cmdlets to create new Orgs, Org VDCs and Users.

Get notification of new blog postings and more by following VMware PowerCLI on Twitter: @PowerCLI

Linking your vCloud Director VMs and vSphere VMs

AlanFeb2012_thumb_thumb1_thumb
Posted by
Alan Renouf
Technical Marketing

One of PowerShell’s great strengths is its ability to take the output of one cmdlet and pipe it into another object, this enables you to create powerfull one line scripts which can be used to change multiple machines very easily.  PowerCLI is no exception, with a single line of code we can already add a portgroup to multiple hosts, create thousands of VMs or disconnect CD-ROMs from hundreds of VMs which would otherwise take days or hours in the vSphere Client.

With the introduction of PowerCLI 5.0.1 we now have multiple cmdlets to manage our vCD environment, but have you ever tried piping the vCD cmdlets into a vSphere PowerCLI cmdlet ?

Lets see what happens?

Firstly we can easily retrieve a Cloud VM object which is part of a particular vApp by using the following cmdlets together:

PS C:\> Get-CIVApp DOMAIN01 | Get-CIVM DOMCON | Format-List

ExtensionData   : VMware.VimAutomation.Cloud.Views.Vm
Status          : PoweredOff
Deleted         : False
GuestOsFullName : Red Hat Enterprise Linux 5 (32-bit)
CpuCount        : 1
MemoryMB        : 256
VMVersion       : v8
Org             : Tenant01
OrgVdc          : Bronze
VApp            : Domain01
Description     :
Href            :
https://vCloud/api/vApp/vm-4b2446a8-b3da-415e-adab-d5e85887ad71
Id              : urn:vcloud:vm:4b2446a8-b3da-415e-adab-d5e85887ad71
Name            : DOMCON

Now lets add in a PowerCLI cmdlet and see what happens, for example, lets try and see what Network adapter and the details for this adapter using the PowerCLI (not vCD PowerCLI) cmdlet called Get-NetworkAdapter.  For this to work you must use the Connect-CIServer cmdlet to first connect to your cloud infrastructure and then the Connect-VIServer cmdlet to connect to any vCenter instances this cloud uses, these connections will need to be in the same session.

PS C:\> Get-CIVApp DOMAIN01 | Get-CIVM DOMCON | Get-NetworkAdapter


Get-NetworkAdapter : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:59 + Get-CIVApp DOMAIN01 | Get-CIVM DOMCON | Get-NetworkAdapter <<<< + CategoryInfo          : InvalidArgument: (DOMCON:PSObject) [Get-NetworkAdapter], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,VMware.VimAutomation.ViCore.Cmdlets.Commands.VirtualDevice.GetNetworkAdapter

As you can see, the Get-NetworkAdapter wasn’t written to understand what the vCD VM object looked like and therefore was unable to display the information.

What can we do ?

Recently there was a couple of great posts by a colleague of mine William Lam, in them he showed how a VM could be linked back to the vCenter it was being hosted on based on various properties which belong to the vCloud object, these posts are well worth a read and can be found here:

So with the information from these posts and knowing with PowerShell it is easy to wrap this in a nice function we can do just that.  Below you will find a function which is called Convert-ToVM which takes the vCloud VM Object and converts it to a vSphere VM, this will then open up all cmdlets which can currently be used against a vSphere VM object to the Cloud VMs.

Warning:  Just as it is not supported to alter or perform actions through the vSphere Client on your vCD hosted VMs, this function should be used with the same considerations in mind.  If you are in any doubt then please check with VMware Support before using this to perform bulk operations on your vCD VMs.

Function Convert-ToVM {
    <#
        .SYNOPSIS
            Converts a vCloud VM into a vCenter VM Object

        .DESCRIPTION
            Converts a vCloud VM into a vCenter VM Object

        .PARAMETER  CIVM
            One or more vCloud VMs
           
        .EXAMPLE
            PS C:\> Get-CIVM | Convert-ToVM
    #>
    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline=$true)]
        $CIVM
    )
    process {
        If (-not $Runonce) {
            Write-Warning "Convert-ToVM should be used for view purposes only, using cmdlets which alter the vSphere VM in any way is not supported and may cause issues.`n"
            $Runonce = $true
        }
        If ((-no
t $DefaultCIServers) -or (-not $DefaultVIServer)){
            Write-Host -ForegroundColor Red "You will need to be connected to both the CIServer and VIServer for this cmdlet to work"
            Return
        }
        Foreach ($VM in $CIVM) { 
            $vsphereVMView = Get-View –RelatedObject $vm.ExtensionData
            Get-VIObjectByVIView $vsphereVMView
        }
    }
}

So now we have this handy function lets see how we can use our previous example to get the network adapter information:

PS C:\> Get-CIVApp DOMAIN01 | Get-CIVM DOMCON | Convert-ToVM | Get-NetworkAdapter | Format-List
WARNING: Convert-ToVM should be used for view purposes only, using cmdlets which alter the vSphere VM in any way is not supported and may cause issues.

MacAddress       : 00:50:56:01:00:05
WakeOnLanEnabled : True
NetworkName      : none
Type             : Flexible
ParentId         : VirtualMachine-vm-97
Parent           : DOMCON (4b2446a8-b3da-415e-adab-d5e85887ad71)
Uid              : /VIServer=administrator@192.168.0.9:443/VirtualMachine=VirtualMachine-vm-97/NetworkAdapter=4000/
ConnectionState  : NotConnected, GuestControl, NoStartConnected
ExtensionData    : VMware.Vim.VirtualPCNet32
Id               : VirtualMachine-vm-97/4000
Name             : Network adapter 1

Another example is where we might want to retrieve the performance statistics of one of our vCloud VMs, lets concentrate on the CPU average usage:

PS C:\> Get-CIVM DOMCON | Convert-ToVM | Get-Stat -stat cpu.usage.average

MetricId                Timestamp                          Value Unit
——–                ———                          —– —-
cpu.usage.average       3/10/2012 12:00:00 AM               1.86 %
cpu.usage.average       3/9/2012 12:00:00 AM                1.83 %
cpu.usage.average       3/8/2012 12:00:00 AM                1.83 %
cpu.usage.average       3/7/2012 12:00:00 AM                1.85 %
cpu.usage.average       3/6/2012 12:00:00 AM                1.86 %
cpu.usage.average       3/5/2012 12:00:00 AM                1.82 %
cpu.usage.average       3/4/2012 12:00:00 AM                1.71 %
cpu.usage.average       3/3/2012 12:00:00 AM                 1.7 %
cpu.usage.average       3/2/2012 12:00:00 AM                1.71 %
cpu.usage.average       3/1/2012 12:00:00 AM                1.71 %
cpu.usage.average       2/29/2012 12:00:00 AM               1.71 %
cpu.usage.average       2/28/2012 12:00:00 AM               1.75 %
cpu.usage.average       2/27/2012 12:00:00 AM                  2 %
cpu.usage.average       2/26/2012 12:00:00 AM               1.83 %
cpu.usage.average       2/25/2012 12:00:00 AM               1.94 %
cpu.usage.average       2/24/2012 12:00:00 AM               2.11 %
cpu.usage.average       2/23/2012 12:00:00 AM               1.83 %

Summary

In summary, using these cmdlets together can give you information which you may not be able to retrieve by other means, but this must be used with extreme caution and any write or change operations must be avoided unless otherwise cleared with VMware support.

Using PowerCLI to export vCloud Director policy settings

AlanFeb2012_thumb_thumb1
Posted by
Alan Renouf
Technical Marketing

Each Organization in vCloud Director has its own policy settings, these are defined when setting up the organization and can be altered through the  vCloud GUI, these define both the vApp lease periods and quotas of VMs which can be running or stored in the Organization.

This can be viewed by right clicking the Organization and selecting Properties and then selecting the Policies tab as below.

image

Recently I was asked by a customer if there was any way to retrieve this information for each Organization in his very populated vCloud Environment, understandably he did not want to right click each Organization and note the information, this could take a long time.

Luckily with PowerCLI 5.0.1 and the vCloud Director Snapin we can use the Get-Org and some custom selections to gain this information with a quick and easy script:

Get-Org | Foreach {
    $_ | Select Name,
    @{N="vAppMaxRuntimeLeaseDays";E={(New-Timespan -Seconds $_.ExtensionData.Settings.vAppLeaseSettings.DeploymentLeaseSeconds).TotalDays}},

    @{N="vAppMaxStorageLeaseDays";E={(New-Timespan -Seconds $_.ExtensionData.Settings.vAppLeaseSettings.StorageLeaseSeconds).TotalDays}},
    @{N="vAppStorageCleanup";E={If ($_.ExtensionData.Settings.vAppLeaseSettings.DeleteOnStorageLeaseExpiration) { "Delete" } Else { "Move"}}},

    @{N="TemplateMaxStorageLeaseDays";E={(New-Timespan -Seconds $_.ExtensionData.Settings.vAppTemplateLeaseSettings.StorageLeaseSeconds).TotalDays}},
    @{N="TemplateStorageCleanup";E={If ($_.ExtensionData.Settings.vAppTemplateLeaseSettings.DeleteOnStorageLeaseExpiration) { "Delete" } Else { "Move"}}},

    @{N="RunningVMQuota";E={$_.DeployedVMQuota}},
    @{N="StoredVMQuota";E={$_.StoredVMQuota}}

}

When run this we will see the results of each Organization within the vCD environment, this is easily exportable using PowerShells built in cmdlets such as Export-CSV or Export-CLiXml or ConvertTo-Html.

Name                        : Tenant01
vAppMaxRuntimeLeaseDays     : 7
vAppMaxStorageLeaseDays     : 30
vAppStorageCleanup          : Move
TemplateMaxStorageLeaseDays : 90
TemplateStorageCleanup      : Move
RunningVMQuota              : 9
StoredVMQuota               : 11

Name                        : Tenant02
vAppMaxRuntimeLeaseDays     : 1
vAppMaxStorageLeaseDays     : 1
vAppStorageCleanup          : Delete
TemplateMaxStorageLeaseDays : 7
TemplateStorageCleanup      : Delete
RunningVMQuota              : 3
StoredVMQuota               : 5

Name                        : Tenant03
vAppMaxRuntimeLeaseDays     : 365
vAppMaxStorageLeaseDays     : 365
vAppStorageCleanup          : Move
TemplateMaxStorageLeaseDays : 365
TemplateStorageCleanup      : Move
RunningVMQuota              : 950
StoredVMQuota               : 1000