Start-IpsVsphereUpgradePvsJob.ps1

<#
.SYNOPSIS
Starts an Image Portability Service job to upgrade the PVS drivers on a VHD(X) image on Vsphere.

.DESCRIPTION
Starts an Image Portability Service job to upgrade the PVS drivers on a VHD(X) image on a SMB fileshare on Vsphere.

.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 Vsphere server.

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

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

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

.PARAMETER SmbDiskName
Specifies the file name of the virtual disk file (VHD(X) on the SMB server that will be updated.

.PARAMETER SmbDiskFormat
Specifies the file format of the disk file that will be updated. 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 SmbOutputDiskSize
Specifies the size in MB of the output virtual disk. Must be greater than or equal to the size of the input virtual disk.

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

.PARAMETER InstallPvs
The specified version of the PVS driver will be installed on the image. The version specified should be the version of the PVS server in Azure, for example 2206, 7.33, or 2203cu1.

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

.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 operation.

.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 operation. If the operation 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 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> $UpgradeParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        SmbHost = 'smbserver.example.com'
        SmbShare = 'disks'
        SmbPath = 'ips'
        SmbDiskName = 'win10-image'
        SmbDiskFormat = 'VhdDiskFormat'
        SmbCwId = 'smbserver-creds'
        SmbOutputDiskName = 'win10-image-efi'
        SmbOutputDiskSize = 71680
        InstallPvs = '2308'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        VsphereCwSecretId = 'vsphere-creds'
        VsphereHost = 'hostname.example.com'
        VsphereSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        VsphereDataCenter = 'datacenter1'
        VsphereDataStore = 'Storage1'
        VsphereCluster = 'Cluster1'
        VsphereNetwork = 'VM Network'
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = 'UpgradeOnVsphere.log'
    }
PS> Start-IpsVsphereUpgradePvsJob @UpgradeParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsVsphereUpgradePvsJob
{
    [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(Mandatory = $true)]
        [int]$SmbOutputDiskSize,
        [Parameter()]
        [string]$SmbDiskFormat = "VhdDiskFormat",
        [Parameter(Mandatory = $true)]
        [string]$SmbCwId,
        [Parameter(Mandatory = $true)]
        [string]$InstallPvs,
        [Parameter()]
        [string]$Deployment,
        [Parameter(Mandatory = $true)]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true)]
        [string]$VsphereCwSecretId,
        [Parameter(Mandatory = $true)]
        [string]$VsphereHost,
        [Parameter(Mandatory = $false)]
        [int]$VspherePort = 443,
        [Parameter()]
        [string]$VsphereSslCaCertificateFilePath,
        [Parameter()]
        [string]$VsphereSslCaCertificate,
        [Parameter()]
        [Alias("VCenterSslFingerprint")]
        [string]$VsphereSslFingerprint,
        [Parameter()]
        [bool]$VsphereSslNoCheckHostname,
        [Parameter(Mandatory = $true)]
        [string]$VsphereDataCenter,
        [Parameter(Mandatory = $true)]
        [string]$VsphereDataStore,
        [Parameter()]
        [string]$VsphereResourcePool,
        [Parameter(Mandatory = $true)]
        [string]$VsphereNetwork,
        [Parameter()]
        [string]$VsphereHostSystem,
        [Parameter()]
        [string]$VsphereCluster,
        [Parameter()]
        [string]$AssetsId,
        [Parameter()]
        [HashTable]$Tags = @{},
        [Parameter()]
        [int]$Timeout = 7200,
        [Parameter()]
        [string]$Prefix = "ce",
        [Parameter()]
        [HashTable]$JobDebug = @{},
        [Parameter()]
        [bool]$DryRun = $false,
        [Parameter()]
        [string]$SecureClientId,
        [Parameter()]
        [string]$SecureSecret,
        [Parameter()]
        [string]$LogFileDir,
        [Parameter()]
        [string]$LogFileName = 'UpgradeOnVsphere.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 $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"
        }

        try {
            LogIt "Starting upgrade PVS workflow"
            Write-Host "***** Call endpoint: images/`$upgradePvs overwrite: $($Force.IsPresent) *****"
            $platformUpgradeData = @{
                platformCredentialId = $VsphereCwSecretId
                vCenterHost = $VsphereHost
                vCenterPort = $VspherePort
                datacenter = $VsphereDataCenter
                datastore = $VsphereDataStore
                network = $VsphereNetwork
                targetDiskName = ""
            }
            if ($VsphereHostSystem)
            {
                $platformUpgradeData['hostSystem'] = $VsphereHostSystem
            }
            if ($VsphereCluster)
            {
                $platformUpgradeData['cluster'] = $VsphereCluster
            }
            if ($VsphereResourcePool)
            {
                $platformUpgradeData['resourcePoolName'] = $VsphereResourcePool
            }
            if ($VsphereSslCaCertificateFilePath -And (Test-Path -Path $VsphereSslCaCertificateFilePath -PathType "Leaf"))
            {
                $platformUpgradeData['vCenterSslCaCertificate'] = ((Get-Content $VsphereSslCaCertificateFilePath) -join "`n") + "`n"
            }
            elseif ($VsphereSslCaCertificate)
            {
                # Replace raw string \n -> PowerShell-readable `n
                $VsphereSslCaCertificate = $VsphereSslCaCertificate.replace("\n", "`n")
                $platformUpgradeData['vCenterSslCaCertificate'] = $VsphereSslCaCertificate
            }
            if ($VsphereSslFingerprint)
            {
                $platformUpgradeData['vCenterSslFingerprint'] = $VsphereSslFingerprint
            }
            if ($VsphereSslNoCheckHostname)
            {
                $platformUpgradeData['vCenterSslNoCheckHostname'] = $VsphereSslNoCheckHostname
            }
            if ($SmbPath) {
                $smbDiskPath = "$SmbShare/$SmbPath"
            } else {
                $smbDiskPath = $SmbShare
            }
            # Add default tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()

            $upgradeData = @{
                platform = "vSphere"
                prefix = $Prefix
                ResourceLocationId = $ResourceLocationId
                timeoutInSeconds = $Timeout
                inputStorageLocation = @{
                    type = "SMB"
                    credentialId = $SmbCwId
                    host = $SmbHost
                    sharePath = $smbDiskPath
                }
                inputImageFilename = $SmbDiskName
                inputImageFormat = $SmbDiskFormat
                outputImageFilename = $SmbOutputDiskName
                outputSizeMb = $SmbOutputDiskSize
                OverwriteOutput = $Force.IsPresent
                upgradeOptions = @{
                    installPvs = $InstallPvs
                }
                tags = $Tags
                debug = $JobDebug
            }
            if ($AssetsId)
            {
                $upgradeData['assetsId'] = $AssetsId
            }

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

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

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