Start-IpsVsphereExportJob.ps1

<#
.SYNOPSIS
Starts an Image Portability Service job to export an image from Vsphere.

.DESCRIPTION
Starts an Image Portability Service job to export an image from Vsphere to a virtual disk file on a SMB fileshare.
Start-IpsVspherePublishJob is an alias for this cmdlet.

.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 SmbLocation
Specifies the SMB URI used to access the SMB server.

.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 HashDisk
Hash the disk before exporting it and return the hash in the job results.

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

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

.PARAMETER SourceDiskName
Specifies the name of the disk that will be exported.

.PARAMETER VsphereHost
Specifies the host name or IP address of the Vsphere server.

.PARAMETER VspherePort
Specifies the network port number of the Vsphere server.

.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 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
Specified 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 VsphereNetwork
Specifies the name of the network on the Vsphere server to use for the export.

.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 VsphereSslFingerprint
Specifies the fingerprint of the Vsphere SSL certificate.

.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 Prefix
Specifies an optional prefix which will be prepended to the name of assets created by the export 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> $ExportParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        SmbLocation = "smb://example.com/share/folder"
        SmbDiskName = 'win10-image'
        SmbDiskFormat = 'VhdDiskFormat'
        SmbCwId = 'smbserver-creds'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        VsphereCwSecretId = 'vsphere-creds'
        VsphereHost = 'hostname.example.com'
        VsphereSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        VsphereDataCenter = 'datacenter1'
        VsphereDataStore = 'Storage1'
        VsphereCluster = 'Cluster1'
        VsphereNetwork = 'VM Network'
        SourceDiskName = '[Storage2] images/win10.vmdk'
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = 'export.log'
    }
PS> Start-IpsVsphereExportJob @ExportParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsVsphereExportJob
{
    [CmdletBinding(DefaultParameterSetName = 'cmd')]
    [Alias("Start-IpsVspherePublishJob")]
    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 = $false, ParameterSetName = 'cmd')]
        [Obsolete("Replaced by SmbLocation.")]
        [string]$SmbHost,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Obsolete("Specifying an alternate SMB port is not supported and this parameter will be ignored.")]
        [string]$SmbPort = $null,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Obsolete("Replaced by SmbLocation.")]
        [string]$SmbShare,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Obsolete("Replaced by SmbLocation.")]
        [uri]$SmbPath,
        [Parameter(Mandatory = $false)]
        [string]$SmbLocation,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SmbDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SmbDiskFormat = "VhdDiskFormat",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SmbCwId,
        [Parameter(Mandatory = $false)]
        [switch]$HashDisk,
        [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,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VsphereNetwork,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereHostSystem,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VsphereCluster,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SourceDiskName,
        [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]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId,
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret,
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir,
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'ExportVsphereToSmb.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
            $SmbLocation = "smb://$($configData.ExportSmb.Host)/$($configData.ExportSmb.Share)/$($configData.ExportSmb.Path)"
            $SmbDiskName = $configData.ExportSmb.DiskName
            $SmbDiskFormat = $configData.ExportSmb.DiskFormat
            if([String]::IsNullOrWhiteSpace($SmbDiskFormat)) { $SmbDiskFormat = "VhdDiskFormat" }
            $SmbCwId = $configData.ExportSmb.CwId
            $Deployment = $configData.Deployment
            if($configData.psobject.Properties.name -contains "ExportResourceLocationId") { $ResourceLocationId = $configData.ExportResourceLocationId }
            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
            $VsphereSslFingerprint = $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
            $SourceDiskName = $configData.SourceDiskName
            $AssetsId = $configData.AssetsId
            if($configData.psobject.Properties.name -contains "Tags") { $Tags = Convert-Object $$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-Object $configData.Debug
            }
        }

        if ($null -eq $SmbLocation)
        {
            if (-not($SmbHost) -or -not($SmbShare))
            {
                LogFatal "Parameter SmbLocation is required"
            }
            if ($SmbPath) {
                $smbDiskPath = "$SmbShare/$SmbPath"
            } else {
                $smbDiskPath = $SmbShare
            }
            $SmbLocation = [System.UriBuilder]::new('smb', $SmbHost, -1, $smbDiskPath)
        }

        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"
        }

        # Export
        try {
            LogIt "Starting export workflow"
            #
            # Run the export workflow
            #
            Write-Host "***** Call Method: ExportImageJob overwrite: $($Force.IsPresent) *****"
            $platformExportData = @{
                platformCredentialId = $VsphereCwSecretId
                vCenterHost = $VsphereHost
                vCenterPort = $VspherePort
                datacenter = $VsphereDataCenter
                datastore = $VsphereDataStore
                network = $VsphereNetwork
                sourceDiskName = $SourceDiskName
            }
            if ($VsphereHostSystem)
            {
                $platformExportData['hostSystem'] = $VsphereHostSystem
            }
            if ($VsphereCluster)
            {
                $platformExportData['cluster'] = $VsphereCluster
            }
            if ($VsphereResourcePool)
            {
                $platformExportData['resourcePoolName'] = $VsphereResourcePool
            }
            if ($VsphereSslCaCertificateFilePath -And (Test-Path -Path $VsphereSslCaCertificateFilePath -PathType "Leaf"))
            {
                $platformExportData['vCenterSslCaCertificate'] = ((Get-Content $VsphereSslCaCertificateFilePath) -join "`n") + "`n"
            }
            elseif ($VsphereSslCaCertificate)
            {
                # Replace raw string \n -> PowerShell-readable `n
                $VsphereSslCaCertificate = $VsphereSslCaCertificate.replace("\n", "`n")
                $platformExportData['vCenterSslCaCertificate'] = $VsphereSslCaCertificate
            }
            if ($VsphereSslFingerprint)
            {
                $platformExportData['vCenterSslFingerprint'] = $VsphereSslFingerprint
            }
            if ($VsphereSslNoCheckHostname)
            {
                $platformExportData['vCenterSslNoCheckHostname'] = $VsphereSslNoCheckHostname
            }

            # Add default tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()

            $exportData = @{
                platform = "vSphere"
                prefix = $Prefix
                ResourceLocationId = $ResourceLocationId
                timeoutInSeconds = $Timeout
                outputStorageLocation = @{
                    Location = $SmbLocation
                    credentialId = $SmbCwId
                }
                outputImageFilename = $SmbDiskName
                outputImageFormat = $SmbDiskFormat
                hashDisk = $HashDisk.IsPresent
                provisionType = "Thin"
                overwriteTargetFile = $Force.IsPresent
                tags = $Tags
                debug = $JobDebug
            }
            if ($AssetsId)
            {
                $exportData['assetsId'] = $AssetsId
            }

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

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

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

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