Start-IpsXenExportJob.ps1

<#

.SYNOPSIS
Implement an Xen image export job.

.DESCRIPTION
Implement an Xen image export job. This function supports exporting an image from a Xen platform
to a virtual disk file on SMB file share server.

.PARAMETER CustomerId
Specifies the Citrix customer id to run the command as.

.PARAMETER SecureClientId
Specifies the id of the access client for the Citrix customer that the export will be performed as.

.PARAMETER SecureSecret
Specifies the secret for the access client for the Citrix customer that the export will be performed as.

.PARAMETER SmbHost
Specifies the host name or IP address of the SMB server to export to.

.PARAMETER SmbShare
Specifies the share on the SMB server to export to.

.PARAMETER SmbPath
Specifies the path on the share of the SMB server to export 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 ResourceLocationId
Specifies the UUID of the resource location of the Xen server.

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

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

.PARAMETER XenPort
Specifies the network port number of the Xen server. The default value is 443.

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

.PARAMETER SourceDiskUuid
Specifies the UUID of the image on the Xen server that will be exported.

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

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

.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 paramters specified are reported. No actual changes are made.

.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. 'ExportXenToSmb.log' is the default.

.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. Consumed by the Wait-IpsJob commandlet.

.EXAMPLE
PS> $ExportParams = @{
        CustomerId = 'your Citrix customer ID'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = 'your Citrix secure secret'
        SmbHost = 'smbserver.example.com'
        SmbShare = 'disks'
        SmbPath = 'ips'
        SmbDiskName = 'marketing-image'
        SmbDiskFormat = 'VhdDiskFormat'
        SmbCwId = 'smbserver-creds'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CwSecretId = 'xen-creds'
        XenHost = 'hostname.example.com'
        XenSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        SourceDiskUuid = '123e4567-e89b-12d3-a456-426655440000'
        Network = 'VM Network'
        StorageRepositoryUuid = '9496efec-cdf6-4019-a251-4ee57ab5643f'
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\XenExport.log'
    }
PS> Start-IpsXenExportJob @ExportParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>

Function Start-IpsXenExportJob
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [string]$CustomerId,
        [Parameter(Mandatory = $true)]
        [string]$SmbHost,
        [Parameter(Mandatory = $true)]
        [string]$SmbShare,
        [Parameter()]
        [string]$SmbPath,
        [Parameter(Mandatory = $true)]
        [string]$SmbDiskName,
        [Parameter()]
        [string]$SmbDiskFormat = "VhdxDiskFormat",
        [Parameter(Mandatory = $true)]
        [string]$SmbCwId,
        [Parameter()]
        [string]$Deployment,
        [Parameter(Mandatory = $true)]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true)]
        [string]$CwSecretId,
        [Parameter(Mandatory = $true)]
        [string]$XenHost,
        [Parameter()]
        [int]$XenPort = 443,
        [Parameter()]
        [string]$XenSslFingerprint,
        [Parameter(Mandatory = $true)]
        [string]$SourceDiskUuid,
        [Parameter(Mandatory = $true)]
        [string]$Network,
        [Parameter(Mandatory = $true)]
        [string]$StorageRepositoryUuid,
        [Parameter()]
        [string]$AssetsId,
        [Parameter()]
        [int]$Timeout = 7200,
        [Parameter()]
        [string]$Prefix = "ce",
        [Parameter()]
        [bool]$JobDebug,
        [Parameter()]
        [string[]]$Flags,
        [Parameter()]
        [bool]$DryRun = $false,
        [Parameter()]
        [string]$SecureClientId = '',
        [Parameter()]
        [string]$SecureSecret = '',
        [Parameter()]
        [string]$LogFileDir = "",
        [Parameter()]
        [string]$LogFileName = 'ExportXenToSmb.log',
        [Parameter()]
        [switch]$OverwriteLog,
        [Parameter()]
        [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 $LogFileDir $LogFileName $OverwriteLog $Verbose

        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 = $cwSecretId
                host = $XenHost
                port = $XenPort
                sourceDiskUuid = $SourceDiskUuid
                network = $Network
                storageRepositoryUuid = $StorageRepositoryUuid
            }
            if ($XenSslFingerprint)
            {
                $platformExportData['sslFingerprint'] = $XenSslFingerprint
            }
            if ($SmbPath) {
                $smbDiskPath = "$SmbShare\$SmbPath"
            } else {
                $smbDiskPath = $SmbShare
            }

            $exportData = @{
                platform = "Xen"
                prefix = $Prefix
                ResourceLocationId = $ResourceLocationId
                timeoutInSeconds = $Timeout
                outputStorageLocation = @{
                    type = "SMB"
                    credentialId = $SmbCwId
                    host = $SmbHost
                    sharePath = $smbDiskPath
                }
                outputImageFilename = $SmbDiskName
                outputImageFormat = $SmbDiskFormat
                provisionType = "Thin"
                overwriteTargetFile = $Force.IsPresent
            }
            if ($AssetsId)
            {
                $exportData['assetsId'] = $AssetsId
            }
            if ($JobDebug)
            {
                $exportData['debug'] = $JobDebug
            }
            if ($Flags)
            {
                $exportData['flags'] = $Flags
            }
            # 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" $False

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

            try {
                $response = Invoke-CCRestMethod 'Post' $Deployment "images/`$export" $CustomerId $SecureClientId $SecureSecret $query $json
                $JobId = $response.id
                LogIt "Image Export started with id $JobId"
            } catch {
                $JobId = "Job failed to start"
                throw "Failed to start export: $_"
            }
        }
        catch {
            LogFatal "Workflow failed: $_"
        }
        finally {
            $output = [PSCustomObject]@{
                CustomerId = $CustomerId
                Deployment = $Deployment
                JobId = $JobId
                LogFileDir = $LogFileDir
                LogFileName = $LogFileName
                SmbHost = $SmbHost
                SmbShare = $SmbShare
                SmbPath = $SmbPath
                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
            }
        }
    }
}