Start-IpsAzurePrepareAndPublishJob.ps1

<#
.SYNOPSIS
Start an Image Portability Service job to prepare an Azure image and then export it.

.DESCRIPTION
Starts an Image Portability Service job to prepare an Azure image and then export it from Azure to a virtual disk file on a SMB fileshare.

.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 in the cloud. Possible values are Mcs and Pvs.

.PARAMETER AzureCwSecretId
Specifies the credential wallet id for the credentials used to access Azure.

.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 TargetDiskName
Specifies the name of the managed disk that will be prepared.

.PARAMETER TargetSnapshotName
Specifies the name of the snapshot that will be prepared.

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

.PARAMETER AzureSubscriptionId
Specifies the id of the Azure subscription where the prepare will take place.

.PARAMETER AzureLocation
Specifies the Azure location name where the prepare appliance will be created.

.PARAMETER AzureVirtualNetworkResourceGroupName
Specifies the resource group of the vnet that the prepare appliance VM's network interface will be connected to.

.PARAMETER AzureVirtualNetworkName
Specifies the name of the vnet that the prepare appliance VM's network interface will be connected to.

.PARAMETER AzureVirtualNetworkSubnetName
Specifies the name of the vnet subnet that the prepare appliance VM's network interface will be connected to.

.PARAMETER AzureVmResourceGroup
If specified, the prepare appliance VM will be created in the supplied resource group. Otherwise a resource group will be created for the prepare appliance VM and deleted when the prepare operation is complete.

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

.PARAMETER SmbLocation
Specifies the SMB share folder to publish the image to.

.PARAMETER SmbDiskName
Specifies the file name of the disk file that will be exported to the SMB server.

.PARAMETER SmbDiskFormat
Specifies the file format of the disk file that will be exported to the SMB server. Possible values are VhdDiskFormat and VhdxDiskFormat. The default value is VhdxDiskFormat.

.PARAMETER SmbCwId
Specifies the credential wallet id for the credentials used to access the SMB server.

.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 in Azure, 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 Personalization 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 NetworkIsolation
If unspecified, the prepare appliance VM will be network isolated if the Azure user has the permissions required.
If specified with value false, the prepare appliance VM will not be network isolated.
If specified with value true, the prepare appliance VM will be network isolated and the job will fail if the Azure user does not have the permissions required.

.PARAMETER UsePublicIP
If specified, the prepare appliance VM will be given a public IP.

.PARAMETER Timeout
Specifies an optional time limit for the export operation. If the export 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 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 export file is overwritten otherwise the operation will fail if the file specified to export to exists.

.INPUTS
None.

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

.EXAMPLE
PS> $PrepareAndPublishParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        ProvisioningType = 'Mcs'
        AzureCwSecretId = 'azure-creds'
        XdReconfigure = @(
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy cloudy-cc2.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        TargetDiskName = 'ManagedDiskToPrepare'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AzureSubscriptionId = 'd7880448-5087-11ed-bdc3-0242ac120002'
        AzureLocation = 'eastus'
        AzureVirtualNetworkResourceGroupName = 'ips-vnet-rg'
        AzureVirtualNetworkName = 'ips-vnet'
        AzureVirtualNetworkSubnetName = 'ips-vnet-subnet'
        TargetResourceGroup = 'MyDisksResourceGroup'
        SmbLocation = "smb://example.com/share/folder"
        SmbDiskName = 'marketing-image'
        SmbDiskFormat = 'VhdxDiskFormat'
        DomainUnjoin = $True
        InstallMisa = $True
        InstallMcsio = $True
        UpdateLayerRepo = '\\layer-server\LayerShare'
        InstallUpl = $True
        Chkdsk = $True
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
    }
PS> Start-IpsAzurePrepareAndPublishJob @PrepareAndPublishParams -Force -OverwriteLog -Verbose | Wait-IpsJob

.EXAMPLE
PS> $PrepareAndPublishParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        ProvisioningType = 'Pvs'
        AzureCwSecretId = 'azure-creds'
        XdReconfigure = @(
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy cloudy-cc2.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        TargetSnapshotName = 'SnapshotToPrepare'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AzureSubscriptionId = 'd7880448-5087-11ed-bdc3-0242ac120002'
        AzureLocation = 'eastus'
        AzureVirtualNetworkResourceGroupName = 'ips-vnet-rg'
        AzureVirtualNetworkName = 'ips-vnet'
        AzureVirtualNetworkSubnetName = 'ips-vnet-subnet'
        AzureVmResourceGroup = 'ips-appliances-rg'
        TargetResourceGroup = 'MyDisksResourceGroup'
        SmbLocation = "smb://example.com/share/folder"
        SmbDiskName = 'marketing-image'
        SmbDiskFormat = 'VhdxDiskFormat'
        InstallPvs = '2308'
        Defrag = $True
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = 'PrepAndPub.log'
    }
PS> Start-IpsAzurePrepareAndPublishJob @PrepareAndPublishParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsAzurePrepareAndPublishJob
{
    [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')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$CustomerId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [Alias("CloudProvisioningType")]
        [string]$ProvisioningType = "Pvs",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [Alias("CloudCwSecretId")]
        [string]$AzureCwSecretId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [Alias("CloudDiskName")]
        [string]$TargetDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [Alias("CloudSnapshotName")]
        [string]$TargetSnapshotName,
        [Parameter(Mandatory = $false)]
        [string]$Md5Hash,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [psobject[]]$XdReconfigure,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$Deployment,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$AzureSubscriptionId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$AzureLocation = "eastus",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$TargetResourceGroup,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$AzureVirtualNetworkResourceGroupName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$AzureVirtualNetworkName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$AzureVirtualNetworkSubnetName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$NetworkIsolation,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$UsePublicIP = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$AzureVmResourceGroup,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$AssetsId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [int]$Timeout = 20000,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$Prefix,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$CeVmSku = "Standard_D2s_v3",
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [HashTable]$JobDebug = @{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$DomainUnjoin = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$InstallMisa = $true,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$ForceMisa = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$InstallMcsio = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$ForceMcsio = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$InstallPvs,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$UpdateLayerRepo,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$InstallUpl,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$RunCitrixOptimizer,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$Chkdsk,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$Defrag,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$EnableRdp,
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [Obsolete("Replaced by SmbLocation.")]
        [string]$SmbHost,
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [Obsolete("Specifying an alternate SMB port is not supported and this parameter will be ignored.")]
        [string]$SmbPort = $null,
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [Obsolete("Replaced by SmbLocation.")]
        [string]$SmbShare,
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [Obsolete("Replaced by SmbLocation.")]
        [string]$SmbPath,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Uri]$SmbLocation,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$SmbDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [string]$SmbDiskFormat = "VhdxDiskFormat",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $true, ParameterSetName = 'obsoletecmd')]
        [string]$SmbCwId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Parameter(Mandatory = $false, ParameterSetName = 'obsoletecmd')]
        [bool]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId,
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret,
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir,
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'AzurePrepareAndPublish.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

        # 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
            $Deployment = $configData.Deployment
            $DryRun = if ($null -ne $configData.DryRun) { $configData.DryRun } else { $False }
        }
        else
        {
            $configData = $Null
        }

        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 prepareAndPublish workflow"
            #
            # Run the prepare workflow
            #
            Write-Host "***** Call Method: prepareAndPublish *****"
            $Parameters = (GetVariablesAsHash)
            $platformData = Format-AzureData -ConfigData $configData -Parameters $Parameters -Verbose $Verbose
            $preparePublishData = Format-PreparePublishData -Platform "Azure" -ConfigData $configData -Parameters $Parameters -Verbose $Verbose

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

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

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