Start-IpsAzureConvertToUefiJob.ps1

<#
.SYNOPSIS
Starts an Image Portability Service job to convert a VHD(X) image from MBR/BIOS to EFI/GPT on Azure.

.DESCRIPTION
Starts an Image Portability Service job to convert a VHD(X) image on a SMB fileshare from MBR/BIOS to EFI/GPT on Azure.

.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 CloudCwSecretId
Specifies the credential wallet id for the credentials used to access Azure.

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

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

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

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

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

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

.PARAMETER SmbHost
Specifies the host name or IP address of the SMB server where the disk that will be converted is.

.PARAMETER SmbShare
Specifies the share on the SMB server where the disk that will be converted is.

.PARAMETER SmbPath
Specifies the path on the share of the SMB server where the disk that will be converted is.

.PARAMETER SmbDiskName
Specifies the file name of the disk file on the SMB server that will be converted.

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

.PARAMETER SmbOutputDiskName
Specifies the file name of the disk file on the SMB server that will created and receive the output of the conversion. This new disk will be a differential disk parented by the input disk.

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

.PARAMETER NetworkIsolation
If unspecified, the appliance VM will be network isolated if the Azure user has the permissions required.
If specified with value false, the appliance VM will not be network isolated.
If specified with value true, the 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 appliance VM will be given a public IP.

.PARAMETER Timeout
Specifies an optional time limit for the operation. If the job 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 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> $ConvertParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CloudCwSecretId = 'azure-creds'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AzureSubscriptionId = 'd7880448-5087-11ed-bdc3-0242ac120002'
        AzureLocation = 'eastus'
        AzureVirtualNetworkResourceGroupName = 'ips-vnet-rg'
        AzureVirtualNetworkName = 'ips-vnet'
        AzureVirtualNetworkSubnetName = 'ips-vnet-subnet'
        SmbHost = 'smbserver.example.com'
        SmbShare = 'disks'
        SmbPath = 'ips'
        SmbDiskName = 'marketing-image'
        SmbOutputDiskName = 'marketing-image-efi'
        SmbDiskFormat = 'VhdxDiskFormat'
        Prefix = 'acme'
        Timeout = 7200
    }
PS> Start-IpsAzureConvertToUefiJob @ConvertParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsAzureConvertToUefiJob
{
    [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(Mandatory = $true)]
        [string]$SmbOutputDiskName,
        [Parameter()]
        [string]$SmbDiskFormat = "VhdxDiskFormat",
        [Parameter(Mandatory = $true)]
        [string]$SmbCwId,
        [Parameter(Mandatory = $false)]
        [string]$Deployment,
        [Parameter(Mandatory = $true)]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true)]
        [string]$AzureSubscriptionId,
        [Parameter(Mandatory = $false)]
        [string]$AzureLocation = "eastus",
        [Parameter(Mandatory = $true)]
        [string]$AzureVirtualNetworkResourceGroupName,
        [Parameter(Mandatory = $true)]
        [string]$AzureVirtualNetworkName,
        [Parameter(Mandatory = $true)]
        [string]$AzureVirtualNetworkSubnetName,
        [Parameter(Mandatory = $false)]
        [bool]$NetworkIsolation,
        [Parameter(Mandatory = $false)]
        [bool]$UsePublicIP = $false,
        [Parameter(Mandatory = $true)]
        [string]$CloudCwSecretId,
        [Parameter(Mandatory = $false)]
        [string]$AzureVmResourceGroup,
        [Parameter(Mandatory = $false)]
        [string]$AssetsId,
        [Parameter(Mandatory = $false)]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false)]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false)]
        [string]$Prefix = "ce",
        [Parameter(Mandatory = $false)]
        [string]$CeVmSku = "Standard_D2s_v3",
        [Parameter(Mandatory = $false)]
        [HashTable]$JobDebug = @{},
        [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 = 'ConvertOnAzure.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"
        }

        # Convert
        try {
            LogIt "Starting convert workflow"
            #
            # Run the convert workflow
            #
            Write-Host "***** Call Endpoint: images/`$convertToUefi overwrite: $($Force.IsPresent) *****"
            $platformConvertData = @{
                platformCredentialId = $CloudCwSecretId
                subscriptionId = $AzureSubscriptionId
                azureRegion = $AzureLocation
                VirtualNetworkResourceGroupName = $AzureVirtualNetworkResourceGroupName
                VirtualNetworkName = $AzureVirtualNetworkName
                VirtualNetworkSubnetName = $AzureVirtualNetworkSubnetName
                UsePublicIP = $UsePublicIP
                resourceGroup = $AzureVmResourceGroup
            }

            if ($PSBoundParameters.ContainsKey('NetworkIsolation'))
            {
                $platformConvertData['networkIsolation'] = $NetworkIsolation
            }

            if ($SmbPath) {
                $smbDiskPath = "$SmbShare\$SmbPath"
            } else {
                $smbDiskPath = $SmbShare
            }
            #Add default tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()
            $convertData = @{
                platform = "Azure"
                prefix = $Prefix
                CeVmSku = $CeVmSku
                ResourceLocationId = $ResourceLocationId
                timeoutInSeconds = $Timeout
                inputStorageLocation = @{
                    type = "SMB"
                    credentialId = $SmbCwId
                    host = $SmbHost
                    sharePath = $smbDiskPath
                }
                inputImageFilename = $SmbDiskName
                inputImageFormat = $SmbDiskFormat
                outputImageFilename = $SmbOutputDiskName
                OverwriteOutput = $Force.IsPresent
                tags = $Tags
            }
            if ($AssetsId)
            {
                $convertData['assetsId'] = $AssetsId
            }
            $convertData['debug'] = $JobDebug

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

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

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