Start-IpsXenPrepareJob.ps1

<#
.SYNOPSIS
Start an Image Portability Service job to prepare an image on Xen.

.DESCRIPTION
Starts an Image Portability Service job to prepare an image on Xen.

.PARAMETER CustomerId
Specifies the customer id of the Citrix customer running this command.

.PARAMETER SecureClientId
Specifies the client id of the Citrix customer's API client.

.PARAMETER SecureSecret
Specifies the client secret of the Citrix customer's API client.

.PARAMETER ResourceLocationId
Specifies the UUID of the resource location of the Xen server.

.PARAMETER ProvisioningType
Specifies the Citrix provisioning type that will be used on Xen. Possible values are Mcs and Pvs.

.PARAMETER XenCwSecretId
Specifies the credential wallet id for the credentials used to access Xen.

.PARAMETER XdReconfigure
Specifies options for reconfiguring the VDA during prepare. If provided, 'XenDesktopVdaSetup.exe /reconfigure' will be run with the specified options. Acceptable options are /controllers, /portnumber, and /enable_hdx_ports.

.PARAMETER TargetDiskUuid
Specifies the UUID of the image on the Xen server that will be prepared.

.PARAMETER OutputDiskName
If specified, the output of the prepare will be a disk with the supplied name.

.PARAMETER Md5Hash
If specified, validate the target disk md5 hash against the one specified, before preparing it.

.PARAMETER XenHost
Specifies the host name or IP address of the Xen server.

.PARAMETER XenPort
Specifies the network port number of the Xen server.

.PARAMETER XenSslFingerprint
Specifies the fingerprint of the Xen SSL certificate.

.PARAMETER Network
Specifies the name of the network on the Xen server to use for the prepare.

.PARAMETER StorageRepositoryUuid
Specifies the UUID of the storage repository on the Xen server to use for the prepare.

.PARAMETER DomainUnjoin
If specified, the image will be unjoined from the domain during prepare.

.PARAMETER InstallMisa
If specified, and the ProvisioningType is Mcs, the version of MCS security agent that matches the VDA installed on the image, will be installed during prepare.

.PARAMETER ForceMisa
If specified, and the ProvisioningType is Mcs, the latest version of MCS security agent will be installed during prepare.

.PARAMETER InstallMcsio
If specified, the version of the MCS IO driver that matches the VDA installed on the image, will be installed during prepare.

.PARAMETER ForceMcsio
If specified, the latest version of the MCS IO driver will be installed during prepare.

.PARAMETER InstallPvs
If specified, and the ProvisioningType is Pvs, the specified version of the PVS driver will be installed on the image during prepare. The version specified should be the version of the PVS server, for example 2206, 7.33, or 2203cu1.

.PARAMETER UpdateLayerRepo
If specified, the AppLayering layer repository URL in the image will be updated.

.PARAMETER InstallUpl
If specified, the Citrix User Personaliztion Layer will be installed in the image during prepare.

.PARAMETER RunCitrixOptimizer
If specified, run Citrix Optimizer with the default template for the image on the image during prepare.

.PARAMETER Chkdsk
If specified, the Windows chkdsk utility will be run against the image during prepare.

.PARAMETER Defrag
If specified, the Windows defrag utility will be run against the image during prepare.

.PARAMETER Timeout
Specifies an optional time limit for the prepare operation. If the prepare does not complete in less than this time it will fail with a timeout error. The default value is 7200.

.PARAMETER Tags
Specifies a hash table of string values to apply as labels to resources created by the prepare operation.

.PARAMETER Prefix
Specifies an optional prefix which will be prepended to the name of assets created by the prepare operation. The default value is 'ce'.

.PARAMETER DryRun
If specified, a test run is performed and any problems with the parameters specified are reported. No actual changes are made.

.PARAMETER Deployment
Specifies the service address to send the job request to. It defaults to api.layering.cloud.com. This can be used if necessary to send the request to a geo specific deployment such as api.eu.layering.cloud.com.

.PARAMETER LogFileDir
Specifies the path to the file to log to. The local directory is the default.

.PARAMETER LogFileName
Specifies the name of the file to log to.

.PARAMETER OverwriteLog
If specified the log file is overwritten otherwise it is appended to.

.PARAMETER Force
If specified then any existing output file is overwritten otherwise the operation will fail if the file specified to output to exists.

.INPUTS
None.

.OUTPUTS
PSCustomObject. A job description which can be consumed by the Wait-IpsJob cmdlet.

.EXAMPLE
PS> $PrepareParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        XdReconfigure = @(
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy cloudy-cc2.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        StorageRepositoryUuid = '9496efec-cdf6-4019-a251-4ee57ab5643f'
        TargetDiskUuid = '123e4567-e89b-12d3-a456-426655440000'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        XenCwSecretId = 'xen-creds'
        XenHost = 'hostname.example.com'
        XenSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        Network = 'VM Network'
        ProvisioningType = 'Mcs'
        DomainUnjoin = $True
        InstallMisa = $True
        InstallMcsio = $True
        UpdateLayerRepo = '\\layer-server\LayerShare'
        InstallUpl = $True
        Chkdsk = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = '.\PrepareXen.log'
    }
PS> Start-IpsXenPrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob

.EXAMPLE
PS> $PrepareParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        XdReconfigure = @(
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy cloudy-cc2.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        TargetDiskUuid = '123e4567-e89b-12d3-a456-426655440000'
        OutputDiskName = 'prepare-output-disk'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        XenCwSecretId = 'xen-creds'
        XenHost = 'hostname.example.com'
        XenSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        Network = 'VM Network'
        StorageRepositoryUuid = '9496efec-cdf6-4019-a251-4ee57ab5643f'
        ProvisioningType = 'Pvs'
        InstallPvs = '2308'
        Defrag = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = '.\PrepareXen.log'
    }
PS> Start-IpsXenPrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsXenPrepareJob
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [string]$CustomerId,
        [Parameter(Mandatory = $true)]
        [string]$ProvisioningType,
        [Parameter(Mandatory = $true)]
        [string]$StorageRepositoryUuid,
        [Parameter(Mandatory = $true)]
        [string]$TargetDiskUuid,
        [Parameter(Mandatory = $false)]
        [psobject[]]$XdReconfigure,
        [Parameter(Mandatory = $false)]
        [string]$OutputDiskName,
        [Parameter(Mandatory = $false)]
        [string]$Md5Hash,
        [Parameter(Mandatory = $false)]
        [string]$Deployment,
        [Parameter(Mandatory = $true)]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true)]
        [Alias("CwSecretId")]
        [string]$XenCwSecretId,
        [Parameter(Mandatory = $true)]
        [string]$XenHost,
        [Parameter()]
        [int]$XenPort = 443,
        [Parameter()]
        [string]$XenSslFingerprint,
        [Parameter(Mandatory = $true)]
        [string]$Network,
        [Parameter(Mandatory = $false)]
        [string]$AssetsId,
        [Parameter(Mandatory = $false)]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false)]
        [int]$Timeout,
        [Parameter(Mandatory = $false)]
        [string]$Prefix,
        [Parameter(Mandatory = $false)]
        [HashTable]$JobDebug = @{},
        [Parameter(Mandatory = $false)]
        [bool]$DomainUnjoin = $false,
        [Parameter(Mandatory = $false)]
        [bool]$InstallMisa = $true,
        [Parameter(Mandatory = $false)]
        [bool]$ForceMisa = $false,
        [Parameter(Mandatory = $false)]
        [bool]$InstallMcsio = $false,
        [Parameter(Mandatory = $false)]
        [bool]$ForceMcsio = $false,
        [Parameter(Mandatory = $false)]
        [string]$InstallPvs,
        [Parameter(Mandatory = $false)]
        [string]$UpdateLayerRepo,
        [Parameter(Mandatory = $false)]
        [bool]$InstallUpl,
        [Parameter(Mandatory = $false)]
        [bool]$RunCitrixOptimizer,
        [Parameter(Mandatory = $false)]
        [bool]$Chkdsk,
        [Parameter(Mandatory = $false)]
        [bool]$Defrag,
        [Parameter(Mandatory = $false)]
        [bool]$EnableRdp,
        [Parameter(Mandatory = $false)]
        [bool]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId,
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret,
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir,
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'PrepareXen.log',
        [Parameter(Mandatory = $false)]
        [switch]$OverwriteLog,
        [Parameter(Mandatory = $false)]
        [switch]$Force
    )

    Begin
    {
        Add-PSSnapin Citrix.*
    }
    Process
    {
        # Initialize Logger
        # Set parameter 'Verbose' by internal parameter 'VerbosePreference', since the option -Verbose is occupied by powershell cmdlet
        $Verbose = $VerbosePreference -eq 'Continue'
        LogInit $MyInvocation $LogFileDir $LogFileName $OverwriteLog $Verbose

        VersionCheck $Deployment $CustomerId

        try
        {
            # Authenticate to Citrix Cloud
            $parameters = AuthToCitrixCloud $CustomerId $SecureClientId $SecureSecret
            if ([string]::IsNullOrWhiteSpace($SecureClientId) -Or [string]::IsNullOrWhiteSpace($SecureSecret))
            {
                $SecureClientId = $parameters.ApiKey
                $SecureSecret = $parameters.SecretKey
            }
        }
        catch
        {
            LogFatal "Failed to authenticate to Citrix Cloud"
        }

        # Prepare
        try
        {
            LogIt "Starting prepare workflow"
            #
            # Run the prepare workflow
            #
            Write-Host "***** Call Method: PrepareImageJob *****"
            $parameters = GetVariablesAsHash
            $platformData = Format-XenData -Parameters $parameters -Verbose $Verbose
            $prepareData = Format-PrepareData -Platform "Xen" -Parameters $parameters -Verbose $Verbose

            # Convert the object to JSON to use in the POST body (Note: Default depth is 2 when serializing)
            $json = ($prepareData + $platformData) | ConvertTo-Json -Depth 10
            LogIt "$($prepareData["ProvisioningType"]) Prepare POST body $json" $Verbose

            $query = @{
                "async" = $true
                "dryRun" = $DryRun
            }

            # Send the POST
            try
            {
                $response = Invoke-CCRestMethod -method 'Post' -deployment $Deployment -serviceRoute "images/`$prepare" -customerId $CustomerId -secureClientId $SecureClientId -secureSecret $SecureSecret -query $query -json $json
                $JobId = $response.id
                LogIt "Image Prepare started with id $JobId"
            }
            catch
            {
                $JobId = "Job failed to start"
                LogFatal "Failed to start prepare: $_"
            }
        }
        catch
        {
            LogFatalException -Message "Workflow failed" -Exception $_.Exception
        }
        finally
        {
            $output = [PSCustomObject]@{
                CustomerId = $CustomerId
                Deployment = $Deployment
                JobId = $JobId
                LogFileDir = $LogFileDir
                LogFileName = $LogFileName
            }
            Write-Output $output

            # Clear credentials at end of pipeline
            if ($PSCmdlet.MyInvocation.PipelinePosition -eq $PSCmdlet.MyInvocation.PipelineLength)
            {
                Clear-XDCredentials
            }
        }
    }
}