Start-IpsVspherePrepareJob.ps1

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

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

.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 Citrix Connector Appliance in Azure.

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

.PARAMETER VsphereCwSecretId
Specifies the credential wallet id for the credentials used to access Vsphere.

.PARAMETER XdReconfigure
Specifies options to run XenDesktopVdaSetup.exe with during prepare.

.PARAMETER TargetDiskName
Specifies the name of the disk that will be prepared.

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

.PARAMETER VsphereHost
Specifies the hostname of the Vsphere admin console.

.PARAMETER VspherePort
Specifies the network port of the Vsphere admin console.

.PARAMETER VsphereNetwork
Specifies the network port of the Vsphere admin console.

.PARAMETER VsphereHostSystem
Specifies the host system to use for the compositing engine VM compute resources. One of 'cluster' or 'hostSystem' should be specified.

.PARAMETER VsphereCluster
Specifies the cluster to use for the compositing engine VM compute resources. One of 'cluster' or 'hostSystem' should be specified.

.PARAMETER VsphereSslCaCertificateFilePath
Specifies the path to the file containing the Vsphere SSL certificate.

.PARAMETER VsphereSslCaCertificate
Specifies the SSL root CA certificate to use in verifying the vCenter host certificate in vSphere API calls. This is only necessary when the VCenter host certificate isn't signed by a recognized authority. This may be the case for example when it was issued by a VMware Certificate Authority (VMCA). The certificate value must be in PEM format as a single-line string with newlines escaped.

.PARAMETER VCenterSslFingerprint
Specifies the fingerprint/thumbprint of the vCenter host certificate in vSphere API calls. This is used as an alternative method of host verification and if supplied will be done instead of certificate validation.

.PARAMETER VsphereSslNoCheckHostname
If specified, do not check the SSL certificate host name (default $false).

.PARAMETER VsphereDataCenter
Specifies the datacenter where all resources for the job reside.

.PARAMETER VsphereDataStore
Specifies the datastore to use for all storage requirements for the compositing engine VM.

.PARAMETER VsphereResourcePool
Specifies the resource pool to use for the compositing engine VM compute resources. If unspecified and a cluster or host system is supplied the root resource pool for the cluster or host system will be used. If unspecified and no cluster or host system is supplied the first resource pool named 'Resources' found in the datacenter will be used.

.PARAMETER TargetResourceGroup
Specifies the Azure resource group name where the disk that will be prepared is located.

.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 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 UsePublicIP
If specified, the prepare appliance VM will be given a public IP.

.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"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        TargetDiskName = '[Storage2] images/win10.vmdk'
        OutputDiskName = '[Storage2] prepped/win10.vmdk'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        VsphereCwSecretId = 'vsphere-creds'
        VsphereHost = 'hostname.example.com'
        VsphereSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        VsphereDataCenter = 'datacenter1'
        VsphereDataStore = 'Storage1'
        VsphereCluster = 'Cluster1'
        VsphereNetwork = 'VM Network'
        ProvisioningType = 'Mcs'
        DomainUnjoin = $True
        InstallMisa = $True
        InstallMcsio = $True
        UpdateLayerRepo = '\\layer-server\LayerShare'
        InstallUpl = $True
        Chkdsk = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = '.\PrepareVsphere.log'
    }
PS> Start-IpsVspherePrepareJob @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"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        TargetDiskName = 'ds:///vmfs/767cf288-57c3-49ac-bb55-10708691ee7a/volumes/images/win10.vmdk'
        OutputDiskName = 'ds:///vmfs/767cf288-57c3-49ac-bb55-10708691ee7a/volumes/prepped/win10.vmdk'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        VsphereCwSecretId = 'vsphere-creds'
        VsphereHost = 'hostname.example.com'
        VsphereSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        VsphereDataCenter = 'datacenter1
        VsphereDataStore = 'Storage1'
        VsphereCluster = 'Cluster1'
        VsphereNetwork = 'VM Network'
        ProvisioningType = 'Pvs'
        InstallPvs = '2308'
        Defrag = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = '.\PrepareVsphere.log'
    }
PS> Start-IpsVspherePrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsVspherePrepareJob
{
    [CmdletBinding(DefaultParameterSetName = 'cmd')]
    Param(
        [Parameter(Mandatory = $true, ParameterSetName = 'file')]
        [Obsolete("Use command-line arguments as input of configuration data.")]
        [string]$ConfigJsonFile,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$CustomerId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$ProvisioningType,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$TargetDiskName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [psobject[]]$XdReconfigure,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$OutputDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Deployment,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VsphereCwSecretId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VsphereHost,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$VspherePort = 443,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereSslCaCertificateFilePath,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereSslCaCertificate,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Alias("VCenterSslFingerprint")]
        [string]$VsphereSslFingerprint,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$VsphereSslNoCheckHostname,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VsphereDataCenter,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VsphereDataStore,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereResourcePool = "Resources",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VsphereNetwork,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereHostSystem,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereCluster,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$AssetsId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Prefix = "ce",
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [HashTable]$JobDebug = @{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$DomainUnjoin = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$InstallMisa = $true,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$ForceMisa = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$InstallMcsio = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$ForceMcsio = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$InstallPvs,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$UpdateLayerRepo,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$InstallUpl,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$Chkdsk,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$Defrag,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$EnableRdp,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId,
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret,
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir,
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'PrepareVsphere.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
        if ($VerbosePreference -eq 'Continue')
        {
            $Verbose = $True
        } else {
            $Verbose = $False
        }
        LogInit $MyInvocation $LogFileDir $LogFileName $OverwriteLog $Verbose

        VersionCheck $Deployment $CustomerId

        # Initialize config data
        if ($PSCmdlet.ParameterSetName -eq 'file') {
            LogIt "Loading config from $ConfigJsonFile"
            $configData = Get-Content -Raw -Path $ConfigJsonFile | ConvertFrom-Json
            LogIt "Config: $configData" $False
            $CustomerId = $configData.CustomerId
            $ProvisioningType = $configData.ProvisioningType
            $TargetDiskName = $configData.SourceDiskName
            $XdReconfigure = $configData.XdReconfigure
            $OutputDiskName = $configData.OutputDiskName
            $Deployment = $configData.Deployment
            if($configData.psobject.Properties.name -contains "PrepareResourceLocationId") { $ResourceLocationId = $configData.PrepareResourceLocationId }
            else { $ResourceLocationId = $configData.ResourceLocationId }
            $VsphereCwSecretId = $configData.VsphereCwSecretId
            $VsphereHost = $configData.VsphereHost
            if([String]::IsNullOrWhiteSpace($configData.VspherePort)) { $VspherePort = 443 }
            else { $VspherePort = [int]$configData.VspherePort }
            $VsphereSslCaCertificate = $configData.VsphereSslCaCertificate
            $VCenterSslFingerprint = $configData.VCenterSslFingerprint
            $VsphereSslNoCheckHostname = $configData.VsphereSslNoCheckHostname
            $VsphereDataCenter = $configData.VsphereDataCenter
            $VsphereDataStore = $configData.VsphereDataStore
            if($configData.psobject.Properties.name -contains "VsphereHostSystem") { $VsphereHostSystem = $configData.VsphereHostSystem }
            if($configData.psobject.Properties.name -contains "VsphereCluster") { $VsphereHostSystem = $configData.VsphereCluster }
            $VsphereResourcePool = $configData.VsphereResourcePool
            $VsphereNetwork = $configData.VsphereNetwork
            $AssetsId = $configData.AssetsId
            if($configData.psobject.Properties.name -contains "Tags") { $Tags = Convert-ObjectToHashtable $$configData.Tags }
            if([String]::IsNullOrWhiteSpace($configData.Timeout)) {
                $Timeout = 7200
            } else {
                $Timeout = [int]$configData.Timeout
            }
            if([String]::IsNullOrWhiteSpace($configData.Prefix)) { $Prefix = "ce" }
            else { $Prefix = $configData.Prefix }
            if(-not([String]::IsNullOrWhiteSpace($configData.Debug)))
            {
                $JobDebug = Convert-ObjectToHashtable $configData.Debug
            }
            $DomainUnjoin = $configData.DomainUnjoin
            $InstallMisa = $configData.InstallMisa
            $ForceMisa = $configData.ForceMisa
            $InstallMcsio = $configData.InstallMcsio
            $ForceMcsio = $configData.ForceMcsio
            $InstallPvs = $configData.InstallPvs
            $UpdateLayerRepo = $configData.UpdateLayerRepo
            $InstallUpl = $configData.InstallUpl
            $Chkdsk = $configData.Chkdsk
            $Defrag = $configData.Defrag
            $EnableRdp = $configData.EnableRdp
        }

        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 *****"
            $platformPrepareData = @{
                vCenterHost = $VsphereHost
                vCenterPort = $VspherePort
                datacenter = $VsphereDataCenter
                datastore = $VsphereDataStore
                network = $VsphereNetwork
                targetDiskName = $TargetDiskName
            }
            if ($VsphereHostSystem)
            {
                $platformPrepareData['hostSystem'] = $VsphereHostSystem
            }
            if ($VsphereCluster)
            {
                $platformPrepareData['cluster'] = $VsphereCluster
            }
            if ($VsphereResourcePool)
            {
                $platformPrepareData['resourcePoolName'] = $VsphereResourcePool
            }
            if ($VsphereSslCaCertificateFilePath -And (Test-Path -Path $VsphereSslCaCertificateFilePath -PathType "Leaf"))
            {
                $platformPrepareData['vCenterSslCaCertificate'] = ((Get-Content $VsphereSslCaCertificateFilePath) -join "`n") + "`n"
            }
            elseif ($VsphereSslCaCertificate)
            {
                # Replace raw string \n -> PowerShell-readable `n
                $VsphereSslCaCertificate = $VsphereSslCaCertificate.replace("\n", "`n")
                $platformPrepareData['vCenterSslCaCertificate'] = $VsphereSslCaCertificate
            }
            if ($VCenterSslFingerprint)
            {
                $platformPrepareData['vCenterSslFingerprint'] = $VCenterSslFingerprint
            }
            if ($VsphereSslNoCheckHostname)
            {
                $platformPrepareData['vCenterSslNoCheckHostname'] = $VsphereSslNoCheckHostname
            }
            #Add default tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()
            $prepareData = @{
                platform = "vSphere"
                provisioningType = $ProvisioningType
                platformCredentialId = $VsphereCwSecretId
                resourceLocationId = $ResourceLocationId
                XdReconfigure = $XdReconfigure
                tags = $Tags
                timeoutInSeconds = $Timeout
                prefix = $Prefix
                overwriteTargetFile = $Force.IsPresent
            }
            if ($DomainUnjoin)
            {
                $prepareData['domainUnjoin'] = $DomainUnjoin
            }
            if ($UpdateLayerRepo)
            {
                $prepareData['updateLayerRepo'] = $UpdateLayerRepo
            }
            if ($InstallUpl)
            {
                $prepareData['installUpl'] = $InstallUpl
            }
            if ($provisioningType -eq "Pvs")
            {
                if ($InstallPvs)
                {
                   $prepareData['installPvs'] = $InstallPvs
                }
                $prepareData['installMisa'] = $false
                $prepareData['forceMisa'] = $false
                $prepareData['installMcsio'] = $false
                $prepareData['forceMcsio'] = $false
            }
            elseif ($provisioningType -eq "Mcs")
            {
                $prepareData['installMisa'] = $InstallMisa
                $prepareData['forceMisa'] = $ForceMisa
                $prepareData['installMcsio'] = $InstallMcsio
                $prepareData['forceMcsio'] = $ForceMcsio
            }
            if ($Chkdsk)
            {
                $prepareData['chkdsk'] = $Chkdsk
            }
            if ($Defrag)
            {
                $prepareData['defrag'] = $Defrag
            }
            if ($EnableRdp)
            {
                $prepareData['enableRdp'] = $EnableRdp
            }
            if ($AssetsId)
            {
                $prepareData['assetsId'] = $AssetsId
            }
            if ($OutputDiskName)
            {
                $prepareData['outputDiskName'] = $OutputDiskName
            }
            $prepareData['debug'] = $JobDebug

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

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

            # Send the POST
            try {
                $response = Invoke-CCRestMethod 'Post' $Deployment "images/`$prepare" $CustomerId $SecureClientId $SecureSecret $query $json
                $JobId = $response.id
                LogIt "Image Prepare started with id $JobId"
            } catch {
                $JobId = "Job failed to start"
                throw "Failed to start prepare: $_"
            }
        }
        catch {
            LogFatal "Workflow failed: $_"
        }
        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
            }
        }
    }
}