Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Working with PowerShell

Save for later
  • 17 min read
  • 07 Sep 2015

article-image

In this article, you will cover:

  • Retrieving system information – Configuration Service cmdlets
  • Administering hosts and machines – Host and MachineCreation cmdlets
  • Managing additional components – StoreFront Admin and Logging cmdlets

(For more resources related to this topic, see here.)

Introduction

With hundreds or thousands of hosts to configure and machines to deploy, configuring all the components manually could be difficult. As for the previous XenDesktop releases, and also with the XenDesktop 7.6 version, you can find an integrated set of PowerShell modules. With its use, IT technicians are able to reduce the time required to perform management tasks by the creation of PowerShell scripts, which will be used to deploy, manage, and troubleshoot at scale the greatest part of the XenDesktop components.

Working with PowerShell instead of the XenDesktop GUI will give you more flexibility in terms of what kind of operations to execute, having a set of additional features to use during the infrastructure creation and configuration phases.

Retrieving system information – Configuration Service cmdlets

In this recipe, we will use and explain a general-purpose PowerShell cmdlet: the Configuration Service category. This is used to retrieve general configuration parameters, and to obtain information about the implementation of the XenDesktop Configuration Service.

Getting ready

No preliminary tasks are required. You have already installed the Citrix XenDesktop PowerShell SDK during the installation of the Desktop Controller role machine(s).

To be able to run a PowerShell script (.ps1 format), you have to enable the script execution from the PowerShell prompt in the following way, using its application:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

How to do it…

In this section, we will explain and execute the commands associated with the XenDesktop System and Services configuration area:

  1. Connect to one of the Desktop Broker servers, by using a remote Desktop connection, for instance.
  2. Right-click on the PowerShell icon installed on the Windows taskbar and select the Run as Administrator option.
  3. Load the Citrix PowerShell modules by typing the following command and then press the Enter key:
    Asnp Citrix*

    As an alternative to the Asnp command, you can use the Add-PSSnapin command.

  4. Retrieve the active and configured Desktop Controller features by running the following command:
    Get-ConfigEnabledFeature

  5. To retrieve the current status of the Config Service, run the following command. The output result will be OK in the absence of configuration issues:
    Get-ConfigServiceStatus

  6. To get the connection string used by the Configuration Service and to connect to the XenDesktop database, run the following command:
    Get-ConfigDBConnection

  7. Starting from the previously received output, it's possible to configure the connection string to let the Configuration Service use the system DB. For this command, you have to specify the Server, Initial Catalog, and Integrated Security parameters:
    Set-ConfigDBConnection –DBConnection"Server=<ServernameInstanceName>; Initial Catalog=<DatabaseName>; Integrated Security=<True | False>"

  8. Starting from an existing Citrix database, you can generate a SQL procedure file to use as a backup to recreate the database. Run the following command to complete this task, specifying the DatabaseName and ServiceGroupName parameters:
    Get-ConfigDBSchema -DatabaseName<DatabaseName> -ServiceGroupName<ServiceGroupName>> Path:FileName.sql

    You need to configure a destination database with the same name as that of the source DB, otherwise the script will fail!

  9. To retrieve information about the active Configuration Service objects (Instance, Service, and Service Group), run the following three commands respectively:
    Get-ConfigRegisteredServiceInstance
    Get-ConfigService
    Get-ConfigServiceGroup

  10. To test a set of operations to check the status of the Configuration Service, run the following script:
    #------------ Script - Configuration Service
    #------------ Define Variables
    $Server_Conn="SqlDatabaseServer.xdseven.localCITRIX,1434"
    $Catalog_Conn="CitrixXD7-Site-First"
    #------------
    write-Host"XenDesktop - Configuration Service CmdLets"
    #---------- Clear the existing Configuration Service DB connection
    $Clear = Set-ConfigDBConnection -DBConnection $null
    Write-Host "Clearing any previous DB connection - Status: " $Clear
    #---------- Set the Configuration Service DB connection string
    $New_Conn = Set-ConfigDBConnection -DBConnection"Server=$Server_Conn; Initial Catalog=$Catalog_Conn; Integrated Security=$true"
    Write-Host "Configuring the DB string connection - Status: " $New_Conn
    $Configured_String = Get-configDBConnection
    Write-Host "The new configured DB connection string is: " $Configured_String
    

    You have to save this script with the .ps1 extension, in order to invoke it with PowerShell. Be sure to change the specific parameters related to your infrastructure, in order to be able to run the script.

    This is shown in the following screenshot:

    working-powershell-img-0

How it works...

The Configuration Service cmdlets of XenDesktop PowerShell permit the managing of the Configuration Service and its related information: the Metadata for the entire XenDesktop infrastructure, the Service instances registered within the VDI architecture, and the collections of these services, called Service Groups.

This set of commands offers the ability to retrieve and check the DB connection string to contact the configured XenDesktop SQL Server database. These operations are permitted by the Get-ConfigDBConnection command (to retrieve the current configuration) and the Set-ConfigDBConnection command (to configure the DB connection string); both the commands use the DB Server Name with the Instance name, DB name, and Integrated Security as information fields.

In the attached script, we have regenerated a database connection string. To be sure to be able to recreate it, first of all we have cleared any existing connection, setting it to null (verify the command associated with the $Clear variable), then we have defined the $New_Conn variable, using the Set-ConfigDBConnection command; all the parameters are defined at the top of the script, in the form of variables.

Use the Write-Host command to echo results on the standard output.

There's more...

In some cases, you may need to retrieve the state of the registered services, in order to verify their availability. You can use the Test-ConfigServiceInstanceAvailability cmdlet, retrieving whether the service is responding or not and its response time. Run the following example to test the use of this command:

Get-ConfigRegisteredServiceInstance | Test-ConfigServiceInstanceAvailability | more

Use the –ForceWaitForOneOfEachType parameter to stop the check for a service category, when one of its services responds.

Administering hosts and machines – Host and MachineCreation cmdlets

In this recipe, we will describe how to create the connection between the Hypervisor and the XenDesktop servers, and the way to generate machines to assign to the end users, all by using Citrix PowerShell.

Getting ready

No preliminary tasks are required. You have already installed the Citrix XenDesktop PowerShell SDK during the installation of the Desktop Controller role machine(s).

To be sure to be able to run a PowerShell script (the.ps1 format), you have to enable the script execution from the PowerShell prompt in this way:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

How to do it…

In this section, we will discuss the PowerShell commands used to connect XenDesktop with the supported hypervisors plus the creation of the machines from the command line:

  1. Connect to one of the Desktop Broker servers.
  2. Click on the PowerShell icon installed on the Windows taskbar.
  3. Load the Citrix PowerShell modules by typing the following command, and then press the Enter key:
    Asnp Citrix*

  4. To list the available Hypervisor types, execute this task:
    Get-HypHypervisorPlugin –AdminAddress<BrokerAddress>

  5. To list the configured properties for the XenDesktop root-level location (XDHyp:), execute the following command:
    Get-ChildItemXDHyp:HostingUnits

    Please refer to the PSPath, Storage, and PersonalvDiskStorage output fields to retrieve information on the storage configuration.

  6. Execute the following cmdlet to add a storage resource to the XenDesktop Controller host:
    Add-HypHostingUnitStorage –LiteralPath<HostPathLocation> -StoragePath<StoragePath> -StorageType<OSStorage|PersonalvDiskStorage> - AdminAddress<BrokerAddress>

  7. To generate a snapshot for an existing VM, perform the following task:

    New-HypVMSnapshot –LiteralPath<HostPathLocation> -SnapshotDescription<Description>

    Use the Get-HypVMMacAddress -LiteralPath<HostPathLocation> command to list the MAC address of specified desktop VMs.

  8. To provision machine instances starting from the Desktop base image template, run the following command:
    New-ProvScheme –ProvisioningSchemeName<SchemeName> -HostingUnitName<HypervisorServer> -IdentityPoolName<PoolName> -MasterImageVM<BaseImageTemplatePath> -VMMemoryMB<MemoryAssigned> -VMCpuCount<NumberofCPU>

  9. To specify the creation of instances with the Personal vDisk technology, use the following option:
    -UsePersonalVDiskStorage.

  10. After the creation process, retrieve the provisioning scheme information by running the following command:
    Get-ProvScheme –ProvisioningSchemeName<SchemeName>

    To modify the resources assigned to desktop instances in a provisioning scheme, use the Set-ProvScheme cmdlet. The permitted parameters are –ProvisioningSchemeName, -VMCpuCount, and –VMMemoryMB.

  11. To update the desktop instances to the latest version of the Desktop base image template, run the following cmdlet:
    Publish-ProvMasterVmImage –ProvisioningSchemeName<SchemeName> -MasterImageVM<BaseImageTemplatePath>

    If you do not want to maintain the pre-update instance version to use as a restore checkpoint, use the –DoNotStoreOldImage option.

  12. To create machine instances, based on the previously configured provisioning scheme for an MCS architecture, run this command:
    New-ProvVM –ProvisioningSchemeName<SchemeName> -ADAccountName"DomainMachineAccount"

    Use the -FastBuild option to make the machine creation process faster. On the other hand, you cannot start up the machines until the process has been completed.

  13. Retrieve the configured desktop instances by using the next cmdlet:
    Get-ProvVM –ProvisioningSchemeName<SchemeName> -VMName<MachineName>

  14. To remove an existing virtual desktop, use the following command:
    Remove-ProvVM –ProvisioningSchemeName<SchemeName> -VMName<MachineName> -AdminAddress<BrokerAddress>

  15. The next script will combine the use of part of the commands listed in this recipe:
    #------------ Script - Hosting + MCS
    #-----------------------------------
    #------------ Define Variables
    $LitPath = "XDHyp:HostingUnitsVMware01"
    $StorPath = "XDHyp:HostingUnitsVMware01datastore1.storage"
    $Controller_Address="192.168.110.30"
    $HostUnitName = "Vmware01"
    $IDPool = $(Get-AcctIdentityPool -IdentityPoolName VDI-DESKTOP)
    $BaseVMPath = "XDHyp:HostingUnitsVMware01VMXD7-W8MCS-01.vm"
    
    #------------ Creating a storage location
    Add-HypHostingUnitStorage –LiteralPath $LitPath -StoragePath $StorPath -StorageTypeOSStorage -AdminAddress $Controller_Address
    
    #---------- Creating a Provisioning Scheme
    New-ProvScheme –ProvisioningSchemeName Deploy_01 -HostingUnitName $HostUnitName -IdentityPoolName $IDPool.IdentityPoolName -MasterImageVM $BaseVMPathT0-Post.snapshot -VMMemoryMB 4096 -VMCpuCount 2 -CleanOnBoot
    
    #---------- List the VM configured on the Hypervisor Host
    dir $LitPath*.vm
    
    exit
    

How it works...

The Host and MachineCreation cmdlet groups manage the interfacing with the Hypervisor hosts, in terms of machines and storage resources. This allows you to create the desktop instances to assign to the end user, starting from an existing and mapped Desktop virtual machine.

The Get-HypHypervisorPlugin command retrieves and lists the available hypervisors to use to deploy virtual desktops and to configure the storage types. You need to configure an operating system storage area or a Personal vDisk storage zone. The way to map an existing storage location from the Hypervisor to the XenDesktop controller is by running the Add-HypHostingUnitStorage cmdlet. In this case you have to specify the destination path on which the storage object will be created (LiteralPath), the source storage path on the Hypervisor machine(s) (StoragePath), and the StorageType previously discussed. The storage types are in the form of XDHyp:HostingUnits<UnitName>.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime

To list all the configured storage objects, execute the following command:

dirXDHyp:HostingUnits<UnitName> *.storage

After configuring the storage area, we have discussed the Machine Creation Service (MCS) architecture. In this cmdlets collection, we have the availability of commands to generate VM snapshots from which we can deploy desktop instances (New-HypVMSnapshot), and specify a name and a description for the generated disk snapshot. Starting from the available disk image, the New-ProvScheme command permits you to create a resource provisioning scheme, on which to specify the desktop base image, and the resources to assign to the desktop instances (in terms of CPU and RAM -VMCpuCount and –VMMemoryMB), and if generating these virtual desktops in a non-persistent mode (-CleanOnBoot option), with or without the use of the Personal vDisk technology (-UsePersonalVDiskStorage). It's possible to update the deployed instances to the latest base image update through the use of the Publish-ProvMasterVmImage command.

In the generated script, we have located all the main storage locations (the LitPath and StorPath variables) useful to realize a provisioning scheme, then we have implemented a provisioning procedure for a desktop based on an existing base image snapshot, with two vCPUs and 4GB of RAM for the delivered instances, which will be cleaned every time they stop and start (by using the -CleanOnBoot option).

You can navigate the local and remote storage paths configured with the XenDesktop Broker machine; to list an object category (such as VM or Snapshot) you can execute this command:

dirXDHyp:HostingUnits<UnitName>*.<category>

There's more...

The discussed cmdlets also offer you the technique to preserve a virtual desktop from an accidental deletion or unauthorized use. With the Machine Creation cmdlets group, you have the ability to use a particular command, which allows you to lock critical desktops: Lock-ProvVM. This cmdlet requires as parameters the name of the scheme to which they refer (-ProvisioningSchemeName) and the ID of the virtual desktop to lock (-VMID).

You can retrieve the Virtual Machine ID by running the Get-ProvVM command discussed previously.

To revert the machine lock, and free the desktop instance from accidental deletion or improper use, you have to execute the Unlock-ProvVM cmdlet, using the same parameter showed for the lock procedure.

Managing additional components – StoreFrontÔ admin and logging cmdlets

In this recipe, we will use and explain how to manage and configure the StoreFront component, by using the available Citrix PowerShell cmdlets. Moreover, we will explain how to manage and check the configurations for the system logging activities.

Getting ready

No preliminary tasks are required. You have already installed the Citrix XenDesktop PowerShell SDK during the installation of the Desktop Controller role machine(s).

To be able to run a PowerShell script (in the.ps1 format), you have to enable the script execution from the PowerShell prompt in this way:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

How to do it…

In this section, we will explain and execute the commands associated with the Citrix Storefront system:

  1. Connect to one of the Desktop Broker servers.
  2. Click on the PowerShell icon installed on the Windows taskbar.
  3. Load the Citrix PowerShell modules by typing the following command, and then press the Enter key:

    Asnp Citrix*

    To execute a command, you have to press the Enter button after completing the right command syntax.

  4. Retrieve the currently existing StoreFront service instances, by running the following command:
    Get-SfService

    To limit the number of rows as output result, you can add the –MaxRecordCount<value> parameter.

  5. To list the detailed information about the StoreFront service(s) currently configured, execute the following command:
    Get-SfServiceInstance –AdminAddress<ControllerAddress>

    The status of the currently active StoreFront instances can be retrieved by using the Get-SfServiceStatus command. The OK output will confirm the correct service execution.

  6. To list the task history associated with the configured StoreFront instances, you have to run the following command:
    Get-SfTask

    You can filter the desired information for the ID of the researched task (-taskid) and sort the results by the use of the –sortby parameter.

  7. To retrieve the installed database schema versions, you can execute the following command:
    Get-SfInstalledDBVersion

    By applying the –Upgrade and –Downgrade filters, you will receive respectively the schemas for which the database version can be updated or reverted to a previous compatible one.

  8. To modify the StoreFront configurations to register its state on a different database, you can use the following command:
    Set-SfDBConnection-DBConnection<DBConnectionString> -AdminAddress<ControllerAddress>

    Be careful when you specify the database connection string; if not specified, the existing database connections and configurations will be cleared!

  9. To check that the database connection has been correctly configured, the following command is available:
    Test-SfDBConnection-DBConnection<DBConnectionString>-AdminAddress<ControllerAddress>

  10. The second discussed cmdlets allows the logging group to retrieve information about the current status of the logging service and run the following command:
    Get-LogServiceStatus

  11. To verify the language used and whether the logging service has been enabled, run the following command:
    Get-LogSite

    The available configurable locales are en, ja, zh-CN, de, es, and fr. The available states are Enabled, Disabled, NotSupported, and Mandatory. The NotSupported state will show you an incorrect configuration for the listed parameters.

  12. To retrieve detailed information about the running logging service, you have to use the following command:
    Get-LogService

    As discussed earlier for the StoreFront commands, you can filter the output by applying the –MaxRecordCount<value> parameter.

  13. In order to get all the operations logged within a specified time range, run the following command; this will return the global operations count:
    Get-LogSummary –StartDateRange<StartDate>-EndDateRange<EndDate>

    The date format must be the following: AAAA-MM-GGHH:MM:SS.

  14. To list the collected operations per day in the specified time period, run the previous command in the following way:
    Get-LogSummary –StartDateRange<StartDate> -EndDateRange<EndDate>-intervalSeconds 86400

    The value 86400 is the number of seconds that are present in a day.

  15. To retrieve the connection string information about the database on which logging data is stored, execute the following command:
    Get-LogDataStore

  16. To retrieve detailed information about the high level operations performed on the XenDesktop infrastructure, you have to run the following command:
    Get-LogHighLevelOperation –Text <TextincludedintheOperation> -StartTime<FormattedDateandTime> -EndTime<FormattedDateandTime>-IsSuccessful<true | false>-User <DomainUserName>-OperationType<AdminActivity | ConfigurationChange>

    The indicated filters are not mandatory. If you do not apply any filters, all the logged operations will be returned. This could be a very long output.

  17. The same information can be retrieved for the low level system operations in the following way:
    Get-LogLowLevelOperation-StartTime<FormattedDateandTime> -EndTime<FormattedDateandTime> -IsSuccessful<true | false>-User <DomainUserName> -OperationType<AdminActivity | ConfigurationChange>

    In the How it works section we will explain the difference between the high and low level operations.

  18. To log when a high level operation starts and stops respectively, use the following two commands:
    Start-LogHighLevelOperation –Text <OperationDescriptionText>-
    Source <OperationSource> -StartTime<FormattedDateandTime>
    -OperationType<AdminActivity | ConfigurationChange>
    Stop-LogHighLevelOperation –HighLevelOperationId<OperationID>
    -IsSuccessful<true | false>

    The Stop-LogHighLevelOperation must be related to an existing start high level operation, because they are related tasks.

How it works...

Here, we have discussed two new PowerShell command collections for the XenDesktop 7 versions: the cmdlet related to the StoreFront platform; and the activities Logging set of commands.

The first collection is quite limited in terms of operations, despite the other discussed cmdlets. In fact, the only actions permitted with the StoreFront PowerShell set of commands are retrieving configurations and settings about the configured stores and the linked database. More activities can be performed regarding the modification of existing StoreFront clusters, by using the Get-SfCluster, Add-SfServerToCluster, New-SfCluster, and Set-SfCluster set of operations.

More interesting is the PowerShell Logging collection. In this case, you can retrieve all the system-logged data, putting it into two principal categories:

  • High-level operations: These tasks group all the system configuration changes that are executed by using the Desktop Studio, the Desktop Director, or Citrix PowerShell.
  • Low-level operations: This category is related to all the system configuration changes that are executed by a service and not by using the system software's consoles.


With the low level operations command, you can filter for a specific high level operation to which the low level refers, by specifying the -HighLevelOperationId parameter.

This cmdlet category also gives you the ability to track the start and stop of a high level operation, by the use of Start-LogHighLevelOperation and Stop-LogHighLevelOperation. In this second case, you have to specify the previously started high level operation.

There's more...

In case of too much information in the log store, you have the ability to clear all of it. To refresh all the log entries, we use the following command:

Remove-LogOperation -UserName<DBAdministrativeCredentials> -Password <DBUserPassword>-StartDateRange <StartDate> -EndDateRange <EndDate>

The not encrypted –Password parameter can be substituted by –SecurePassword, the password indicated in secure string form.

The credentials must be database administrative credentials, with deleting permissions on the destination database.

This is a not reversible operation, so ensure that you want to delete the logs in the specified time range, or verify that you have some form of data backup.

Resources for Article:


Further resources on this subject: