Start-IpsAhvPrepareJob.ps1

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

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

.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 for the Nutanix server.

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

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

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

.PARAMETER CwSecretId
Specifies the credential wallet id for the credentials used to access the AHV server.

.PARAMETER PrismHost
Specifies the host name or IP address of the Prism Element host.

.PARAMETER PrismPort
Specifies the network port number of the Prism Element host.

.PARAMETER PrismSslCaCertificateFilePath
Specifies the path to the file containing the Prism host SSL certificate.

.PARAMETER PrismSslCaCertificate
Specifies the Prism host SSL certificate as a single string.

.PARAMETER PrismSslFingerprint
Specifies the fingerprint of the Prism SSL certificate. Specified as an alternative to the SSL certificate.

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

.PARAMETER SourceImageName
Specifies the name of the image on the Prism Element host that will be prepared. If the name is not found or is not unique the job will fail with an error. Exactly one of SourceImageName, SourceImageUuid, or SourceVmUuid must be specified.

.PARAMETER SourceImageUuid
Specifies the UUID of the image on the Prism Element host that will be prepared. Exactly one of SourceImageName, SourceImageUuid, or SourceVmUuid must be specified.

.PARAMETER SourceVmUuid
Specifies the UUID of the virtual machine on the Prism Element host that will be prepared. Exactly one of SourceImageName, SourceImageUuid, or SourceVmUuid must be specified.

.PARAMETER ClusterUuid
Specifies the UUID of cluster of the Nutanix system where the source image or virtual machine resides.

.PARAMETER SubnetUuid
Specifies the UUID of subnet of the Nutanix system to use for the export.

.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 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"
            }
        )
        OutputImageName = 'Windows 10 Finance'
        CwSecretId = 'prism-creds'
        PrismHost = 'hostname.example.com'
        PrismPort = 9440
        PrismSslCaCertificate = "-----BEGIN CERTIFICATE-----\nMIIEETCCAvFgAwIBAgIJAPlOYwwTfEIXMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\nVQQDDAJDQTEXMBUGCgmSJomT8ixkARkWB3ZzcGhlcmUxFTBTBgoJkiaJk/IsZAEZ\nFgVsb2NhbDELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFTATBgNV\nBAoMDGR5LXZjZW50ZXItMTEbMBkGA1UECwwSVk13YXJlIEVuZ2luZWVyaW5nMB4X\nDTIwMDcxNDIyNTUwOVoXDTMwMDcxMjIyNTUwOVowgZMxCzAJBgNVBAMMAkNBMRcw\nFQYKCZImiZPyLGQBGRYHdnNwaGVyZTEVMBMGCgmSJomT8ixkARkWBWxvY2FsMQsw\nCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMZHktdmNl\nbnRlci0xMRswGQYDVQQLDBJWTXdhcmUgRW5naW5lZXJpbmcwggEiMA0GCSqGSIb3\nDQEBAQUAA4IBDwAwggEKAoIBAQCXKo6P9K/ORDHqht10efM9EEAA83dxZzABEbUi\nWFpAacwUwkHoMrnlA2/2hW9k88Dm2SiTYEQ5h39EQARhbPXM54BGjccccamxOyKR\nnhU1JbX11A+/cqnQ54ZrSrXQB7c92Ax56cnVv0thU7ZbEnMmmr/JOBMA+KKjvqS9\nbgH2kNr/zCYjYfFNheIwCXyrPECXEzFtFGMIb2SfCbqAiaKedi3AIU93wyAiRrWL\n9LKIbaAaUTysQnHoIItEWYg/ek67t9Z4g4MhMdVwXBd0sgaLe1FCmKoXaV+OY+uQ\nr4b0TxVZOz6gLMaqtFiP1Prq5WLaSwAvf2NNOqzu2HHUxvZZAgMBAAGjZjBkMB0G\nA1UdDgQWBBQ2XJzbpLLliA7Ph7dymvZoCcd3HzAfBgNVHREEGDAWgQ5lbWFpbEBh\nY21lLmNvbYcEfwAAATAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIB\nADANBgkqhkiG9w0BAQsFAAOCAQEAD8VBW5mdqVieJnYSJXWdYaBtehR0WAtBPuth\nmuOhj62t+6zTjHe5OL2OxLHPkDtoLEW9ZIqrrRWSZJ3DPGC0HyXafKTi8r9KVjTL\nuX0AAJ042FotSOB2nYBMSRr69PuXF+fReThutuWZd8Qeo/PHbiLu3V4WCaPKiAnZ\n6+S6n/zNUzfak7e6ZntYqrKeA2U3opSyHwZLQyx49wzmtdYKLUs+gdV2h68nTHV6\nS7iyGr9sPubdzf1P/GN9wyvWA07iFfpx8+ft4PhYExeyMbhv03TUceN7iIzju3CD\n4sdZ66ETY6pBBMP4f7TtQL3wK2DoLkmdqwtzBgPDnqpXsf2bwA==\n-----END CERTIFICATE-----\n"
        PrismSslNoCheckHostname = $False
        SourceImageUuid = '123e4567-e89b-12d3-a456-426655440000'
        ClusterUuid = 'd0659a72-5087-11ed-bdc3-0242ac120002'
        SubnetUuid = 'd7880448-5087-11ed-bdc3-0242ac120002'
        ProvisioningType = 'Mcs'
        DomainUnjoin = $True
        InstallMisa = $True
        InstallMcsio = $True
        UpdateLayerRepo = '\\layer-server\LayerShare'
        InstallUpl = $True
        Chkdsk = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = '.\PrepareNutanix.log'
    }
PS> Start-IpsAhvPrepareJob @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"
            }
        )
        OutputImageName = 'Marketing Desktop'
        CwSecretId = 'prism-creds'
        PrismHost = 'hostname.example.com'
        PrismPort = 9440
        PrismSslCaCertificate = "-----BEGIN CERTIFICATE-----\nMIIEETCCAvFgAwIBAgIJAPlOYwwTfEIXMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\nVQQDDAJDQTEXMBUGCgmSJomT8ixkARkWB3ZzcGhlcmUxFTBTBgoJkiaJk/IsZAEZ\nFgVsb2NhbDELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFTATBgNV\nBAoMDGR5LXZjZW50ZXItMTEbMBkGA1UECwwSVk13YXJlIEVuZ2luZWVyaW5nMB4X\nDTIwMDcxNDIyNTUwOVoXDTMwMDcxMjIyNTUwOVowgZMxCzAJBgNVBAMMAkNBMRcw\nFQYKCZImiZPyLGQBGRYHdnNwaGVyZTEVMBMGCgmSJomT8ixkARkWBWxvY2FsMQsw\nCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMZHktdmNl\nbnRlci0xMRswGQYDVQQLDBJWTXdhcmUgRW5naW5lZXJpbmcwggEiMA0GCSqGSIb3\nDQEBAQUAA4IBDwAwggEKAoIBAQCXKo6P9K/ORDHqht10efM9EEAA83dxZzABEbUi\nWFpAacwUwkHoMrnlA2/2hW9k88Dm2SiTYEQ5h39EQARhbPXM54BGjccccamxOyKR\nnhU1JbX11A+/cqnQ54ZrSrXQB7c92Ax56cnVv0thU7ZbEnMmmr/JOBMA+KKjvqS9\nbgH2kNr/zCYjYfFNheIwCXyrPECXEzFtFGMIb2SfCbqAiaKedi3AIU93wyAiRrWL\n9LKIbaAaUTysQnHoIItEWYg/ek67t9Z4g4MhMdVwXBd0sgaLe1FCmKoXaV+OY+uQ\nr4b0TxVZOz6gLMaqtFiP1Prq5WLaSwAvf2NNOqzu2HHUxvZZAgMBAAGjZjBkMB0G\nA1UdDgQWBBQ2XJzbpLLliA7Ph7dymvZoCcd3HzAfBgNVHREEGDAWgQ5lbWFpbEBh\nY21lLmNvbYcEfwAAATAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIB\nADANBgkqhkiG9w0BAQsFAAOCAQEAD8VBW5mdqVieJnYSJXWdYaBtehR0WAtBPuth\nmuOhj62t+6zTjHe5OL2OxLHPkDtoLEW9ZIqrrRWSZJ3DPGC0HyXafKTi8r9KVjTL\nuX0AAJ042FotSOB2nYBMSRr69PuXF+fReThutuWZd8Qeo/PHbiLu3V4WCaPKiAnZ\n6+S6n/zNUzfak7e6ZntYqrKeA2U3opSyHwZLQyx49wzmtdYKLUs+gdV2h68nTHV6\nS7iyGr9sPubdzf1P/GN9wyvWA07iFfpx8+ft4PhYExeyMbhv03TUceN7iIzju3CD\n4sdZ66ETY6pBBMP4f7TtQL3wK2DoLkmdqwtzBgPDnqpXsf2bwA==\n-----END CERTIFICATE-----\n"
        PrismSslNoCheckHostname = $False
        SourceImageUuid = '123e4567-e89b-12d3-a456-426655440000'
        ClusterUuid = 'd0659a72-5087-11ed-bdc3-0242ac120002'
        SubnetUuid = 'd7880448-5087-11ed-bdc3-0242ac120002'
        ProvisioningType = 'Pvs'
        InstallPvs = '2308'
        Defrag = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = '.\PrepareAhv.log'
    }
PS> Start-IpsAhvPrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsAhvPrepareJob
{
    Param(
        [Parameter(Mandatory = $true)]
        [string]$CustomerId,
        [Parameter(Mandatory = $true)]
        [string]$ProvisioningType,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SourceImageName,
        [Parameter(Mandatory = $false)]
        [string]$SourceImageUuid,
        [Parameter(Mandatory = $false)]
        [string]$SourceVmUuid,
        [Parameter(Mandatory = $true)]
        [string]$ClusterUuid,
        [Parameter(Mandatory = $false)]
        [string]$SubnetUuid,
        [Parameter(Mandatory = $true)]
        [psobject[]]$XdReconfigure,
        [Parameter(Mandatory = $false)]
        [string]$OutputImageName,
        [Parameter(Mandatory = $false)]
        [string]$Deployment,
        [Parameter(Mandatory = $true)]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true)]
        [string]$CwSecretId,
        [Parameter(Mandatory = $true)]
        [string]$PrismHost,
        [Parameter(Mandatory = $false)]
        [int]$PrismPort = 9440,
        [Parameter(Mandatory = $false)]
        [string]$PrismSslCaCertificateFilePath,
        [Parameter(Mandatory = $false)]
        [string]$PrismSslCaCertificate,
        [Parameter(Mandatory = $false)]
        [string]$PrismSslFingerprint,
        [Parameter(Mandatory = $false)]
        [bool]$PrismSslNoCheckHostname,
        [Parameter(Mandatory = $false)]
        [string]$AssetsId,
        [Parameter(Mandatory = $false)]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false)]
        [string]$Prefix = "ce",
        [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]$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 = 'PrepareAhv.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

        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 AHV prepare workflow"
            #
            # Run the prepare workflow
            #
            Write-Host "***** Call Method: PrepareImageJob *****"
            $platformPrepareData = @{
                host = $PrismHost
                port = $PrismPort
                clusterUuid = $ClusterUuid
                subnetUuid = $SubnetUuid
                sourceImageUuid = $SourceImageUuid
            }
            if ($PrismSslCaCertificateFilePath -And (Test-Path -Path $PrismSslCaCertificateFilePath -PathType "Leaf"))
            {
                $platformPrepareData['sslCaCertificate'] = ((Get-Content $PrismSslCaCertificateFilePath) -join "`n") + "`n"
            }
            elseif ($prismSslCaCertificate)
            {
                # Replace raw string \n -> PowerShell-readable `n
                $PrismSslCaCertificate = $PrismSslCaCertificate.replace("\n", "`n")
                $platformPrepareData['sslCaCertificate'] = $PrismSslCaCertificate
            }
            if ($PrismSslFingerprint)
            {
                $platformPrepareData['sslFingerprint'] = $PrismSslFingerprint
            }
            if ($PrismSslNoCheckHostname)
            {
                $platformPrepareData['sslNoCheckHostname'] = $PrismSslNoCheckHostname
            }
            if ($SourceImageName)
            {
                $platformPrepareData['sourceImageName'] = $SourceImageName
            }
            elseif ($SourceImageUuid)
            {
                $platformPrepareData['sourceImageUuid'] = $SourceImageUuid
            }
            elseif ($SourceVmUuid)
            {
                $platformPrepareData['sourceVmUuid'] = $SourceVmUuid
            }
            $prepareData = @{
                platform = "Ahv"
                provisioningType = $ProvisioningType
                platformCredentialId = $CwSecretId
                resourceLocationId = $ResourceLocationId
                XdReconfigure = $XdReconfigure
                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 ($OutputImageName)
            {
                $prepareData['OutputImageName'] = $OutputImageName
            }
            $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
            }
        }
    }
}