Examples of Using View PowerCLI for Enhanced Functionality
You can create PowerShell functions by combining View PowerCLI and vSphere PowerCLI cmdlets to perform complex operations such as resizing pools, and adding datastores to desktop pools. The following sections contain sample functions that you can adapt and apply to your own systems.
Checking if a View Connection Server Instance Is Running
Define a PowerShell function to check if a View Connection Server instance is running, and optionally, start the service.
# WaitForViewStartup
# Parameters
#   $ClearError    If $true, clear the $error object on completion.
#   $StartBroker   If $true, start the service if it is not running.
 
function WaitForViewStartup
{ param ($ClearError = $true, $StartBroker = $true)
    $service = Get-Service wsbroker
    if($service -and (Get-Service wstomcat)){
        $started = $false
        if($service.Status -eq "Stopped"){
            if($StartBroker){ # Start the broker if it is not running.
                Write-Warning "Connection Broker service is stopped, attempting to start."
                $errCountBefore = $error.Count
                Start-Service wsbroker
                $errCountAfter = $error.Count
                if($errorCountAfter -gt $errorCountBefore){
                    break
                }
            } else {
                Write-Error "Connection Broker service is stopped."
                break
            }
        }
        while(!$started){ # Loop until service has completed starting up.
            Write-Warning "Waiting for View Connection Server to start."
            $errCountBefore = $error.Count
            $output = Get-GlobalSetting -ErrorAction SilentlyContinue
            $errCountAfter = $error.Count
            $started = $true
            if($errCountAfter -gt $errCountBefore){
                $err = $error[0].ToString()
                if($err.Contains("NoQueueHandler")){
                    $started = $false
                    Start-Sleep -s 1
                } else {
                    if($ClearError){
                        $error.Clear()
                    }
                    Write-Error $err
                    break
                }
            }
            if($ClearError){
                $error.Clear()
            }
        }
    } else {
        Write-Error "The View Connection Server services could not be found. Is the Connection Server installed?"
    }
}
Resize Automatic and Linked-Clone Desktop Pools
Define PowerShell functions to check the current usage of all desktop pools, and to resize any automatically provisioned or linked-clone desktop pools that are at their maximum capacity.
# PollAllPoolsUsage
# Parameters
#   $increment     Amount by which to increase a pool that is at maximum capacity (default = 5).
 
function PollAllPoolsUsage
{ param ($increment)
 
    if(-not $increment){
        $increment = 5
    }
 
    # Retrieve all pool objects and check each one individually
    $pools = Get-Pool
    foreach ($pool in $pools){
        PollPoolUsage $pool $increment
    }
}
 
# PollPoolUsage
# Parameters
#   $Pool          Pool object that represents the pool to be checked.
#   $increment     Amount by which to increase pool that is at maximum capacity.
 
function PollPoolUsage
{ param ($Pool, $increment)
    # Get a list of remote sessions for the pool (errors are suppressed)
    $remotes = Get-RemoteSession -pool_id $Pool.pool_id -ErrorAction SilentlyContinue
    # Count the remote sessions.
    $remotecount = 0
    if($remotes){
        $remotecount = ([Object[]]($remotes)).Count
    }
 
    # Get a list of local sessions for the pool (errors are suppressed)
    $locals = Get-LocalSession -pool_id $Pool.pool_id -ErrorAction SilentlyContinue
    # Count the local sessions.
    $localcount = 0
            if($locals){
        $localcount = ([Object[]]($locals)).Count
    }
 
    # Calculate the total number of sessions
    $totalcount = $localcount + $remotecount
 
    # Determine the maximum number of desktops configured for a pool.
    $maxdesktops = 0
    if($Pool.deliveryModel -eq "Provisioned"){
        $maxdesktops = $Pool.maximumCount
    } else {
        $maxdesktops = $Pool.machineDNs.split(";").Count
    }
 
    # Output the usage statistics for a pool.
    Write-Output ("==== " + $Pool.pool_id + " ====")
    Write-Output ("Remote session count: " + $remotecount)
    Write-Output ("Local session count: " + $localcount)
    Write-Output ("Total session count: " + $totalcount)
    Write-Output ("Maximum desktops: " + $maxdesktops)
 
    # If a pool is using all its desktops, increase its maximum size
    # or output a warning if it cannot be resized.
    if($maxdesktops -eq $totalcount){
        if($Pool.deliveryModel -eq "Provisioned"){ # Pool type can be resized
            $newmaximum = [int]$Pool.maximumCount + [int]$increment
            if($Pool.desktopSource -eq "VC"){ # Resize an automatic pool
                Update-AutomaticPool -pool_id $Pool.pool_id -maximumCount $newmaximum
            } elseif ($Pool.desktopSource -eq "SVI"){ # Resize a linked-clone pool
                Update-AutomaticLinkedClonePool -pool_id $Pool.pool_id -maximumCount $newmaximum
            }
 
            Write-Output ("Pool " + $Pool.pool_id + " is using 100% of its desktops. Maximum VMs increased to " + $newmaximum)
        } else { # Pool type cannot be resized
            Write-Output ("Pool " + $Pool.pool_id + " is using 100% of its desktops. Consider increasing its capacity.")
        }
    }
}
Determining Paths to vSphere Inventory Objects
Define a PowerShell function that uses vSphere PowerCLI to return the full path to a vSphere inventory object. For a function that you can use to determine datastore paths, see Determining Paths to vSphere Datastore Objects.
# VVGetInventoryPath
# Parameters
#   $InvObject     Inventory object in vSphere PowerCLI.
#
# Examples
#   VVGetInventoryPath (Get-VM -name myVM)
#   VVGetInventoryPath (Get-ResourcePool | Select -first 1)
 
function VVGetPath($InvObject){
    if($InvObject){
 
        $objectType = $InvObject.GetType().Name
        $objectBaseType = $InvObject.GetType().BaseType.Name
        if($objectType.Contains("DatastoreImpl")){
            Write-Error "Use the VVGetDataStorePath function to determine datastore paths."
            break
        }
        if(-not ($objectBaseType.Contains("InventoryItemImpl") -or $objectBaseType.Contains("FolderImpl") -or $objectBaseType.Contains("DatacenterImpl") -or $objectBaseType.Contains("VMHostImpl") ) ){
            Write-Error ("The provided object is not an expected vSphere object type. Object type is " + $objectType)
            break
        }
 
        $path = ""
        # Recursively move up through the inventory hierarchy by parent or folder.
        if($InvObject.ParentId){
            $path = VVGetPath(Get-Inventory -Id $InvObject.ParentId)
        } elseif ($InvObject.FolderId){
            $path = VVGetPath(Get-Folder -Id $InvObject.FolderId)
        }
 
        # Build the path, omitting the "Datacenters" folder at the root.
        if(-not $InvObject.isChildTypeDatacenter){ # Add object to the path.
            $path = $path + "/" + $InvObject.Name
        }
        $path
    }
}
Determining Paths to vSphere Datastore Objects
Define a PowerShell function that uses vSphere PowerCLI to return the full path to a datastore in a cluster as specified by a resource pool.
# VVGetDatastorePath
# Parameters
#   $Datastore     Datastore object in vSphere PowerCLI.
#   $ResourcePool  Resource pool in cluster.
#
#Example
#   VVGetDatastorePath (Get-Datastore "datastore1") (Get-ResourcePool "Resources")
 
function VVGetDatastorePath($Datastore,$ResourcePool){
    if($Datastore -and $ResourcePool){
 
        $dsType = $Datastore.GetType().Name
        $rpType = $ResourcePool.GetType().Name
        if(-not ($dsType.Contains("Datastore")) ){
            Write-Error "The Datastore provided is not a Datastore object."
            break
        }
        if(-not ($rpType.Contains("ResourcePool")) ){
            Write-Error "The Resource Pool provided is not a ResourcePool object."
            break
        }
 
        $ClusterPath = VVGetPath(Get-Inventory -Id $ResourcePool.ParentId)
        $path = $ClusterPath + "/" + $Datastore.Name
        $path
    }
}
Adding and Removing Datastores
Define a PowerShell function to add a datastore to an automatic pool.
# AddDatastoreToAutomaticPool
# Parameters
#   $Pool          Pool ID of pool to be updated.
#   $Datastore     Full path to datastore to be added.
 
function AddDatastoreToAutomaticPool
{ param ($Pool, $Datastore)
    $PoolSettings = (Get-Pool -pool_id $Pool)
    $datastores = $PoolSettings.datastorePaths + ";$Datastore"
    Update-AutomaticPool -pool_id $Pool -datastorePaths $datastores
}
Define a PowerShell function to remove a datastore from an automatic pool.
# RemoveDatastoreFromAutomaticPool
# Parameters
#   $Pool          Pool ID of pool to be updated.
#   $Datastore     Full path to datastore to be removed.
 
function RemoveDatastoreFromAutomaticPool
{ param ($Pool, $Datastore)
    $PoolSettings = (Get-Pool -pool_id $Pool)
    $currentdatastores = $PoolSettings.datastorePaths
 
    $datastores = ""
    foreach ($path in $currentdatastores.split(";")){
        if(-not ($path -eq $Datastore)){
            $datastores = $datastores + "$path;"
        }
    }
    Update-AutomaticPool -pool_id $Pool -datastorePaths $datastores
}
Define a PowerShell function to add a datastore to a linked-clone pool.
# AddDatastoreToLinkedClonePool
# Parameters
#   $Pool          Pool ID of pool to be updated.
#   $Datastore     Full path to datastore to be added.
 
function AddDatastoreToLinkedClonePool
{ param ($Pool, $Datastore)
    $PoolSettings = (Get-Pool -pool_id $Pool)
    $datastores = $PoolSettings.datastoreSpecs + ";$Datastore"
    Update-AutomaticLinkedClonePool -pool_id $Pool -datastoreSpecs $datastores
}
Define a PowerShell function to remove a datastore from a linked-clone pool.
# RemoveDatastoreFromLinkedClonePool
# Parameters
#   $Pool          Pool ID of pool to be updated.
#   $Datastore     Full path to datastore to be removed.
 
function RemoveDatastoreFromLinkedClonePool
{ param ($Pool, $Datastore)
    $PoolSettings = (Get-Pool -pool_id $Pool)
    $currentdatastores = $PoolSettings.datastoreSpecs
 
    $datastores = ""
    foreach ($spec in $currentdatastores.split(";")){
        $path = $spec.split("]")[1]
        $pathToRemove = $Datastore.split("]")[1]
        if(-not $pathToRemove){
            $pathToRemove = $Datastore
        }
        if(-not ($path -eq $pathToRemove)){
            $datastores = $datastores + "$spec;"
        }
    }
    Update-AutomaticLinkedClonePool -pool_id $Pool -datastoreSpecs $datastores
}