HP.Softpaq.psm1

#
# Copyright 2018-2021 HP Development Company, L.P.
# All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains the property of HP Development Company, L.P.
#
# The intellectual and technical concepts contained herein are proprietary to HP Development Company, L.P
# and may be covered by U.S. and Foreign Patents, patents in process, and are protected by
# trade secret or copyright law. Dissemination of this information or reproduction of this material
# is strictly forbidden unless prior written permission is obtained from HP Development Company, L.P.



Set-StrictMode -Version 3.0
#requires -Modules "HP.Private","HP.Firmware"

<#
.SYNOPSIS
    Retrieve softpaq metadata (CVA) can retrieve a CVA or an alternate server.
 
.DESCRIPTION
    Get a softpaq metadata file (CVA) from the location specified by the URL parameter. If URL is not
    specified, the Softpaq metadata is downloaded can retrieve a CVA via HTTPS.
 
.PARAMETER Number
    The softpaq number for which to retrieve the metadata. Do not include prefix such as SP or extension such as .exe, specify the softpaq number only.
 
.PARAMETER Url
    specify an alternate location for the softpaq URL. This URL must be http, https, or ftp. The softpaq CVAs are expected to be at the location
    pointed to by this URL. If not specified, ftp.hp.com is used via HTTPS protocol.
 
.PARAMETER MaxRetries
    Maximum number of retries allowed to obtain an exclusive lock to downloaded files. This is relevant only when
    files are downloaded into a shared directory and multiple processes may be reading or writing from the same
    location.
 
    Current default value is 10 retries, and each retry includes a 30 second pause, which means the maximum time the
  default value will wait for an exclusive logs is 300 seconds or 5 minutes.
 
.EXAMPLE
    Get-SoftpaqMetadata 1234 | Out-SoftpaqField -field Title
 
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Get-SoftpaqMetadataFile](Get-SoftpaqMetadataFile)
 
.LINK
    [Get-SoftpaqList](Get-SoftpaqList)
 
.LINK
    [Out-SoftpaqField](Out-SoftpaqField)
 
.LINK
    [Clear-SoftpaqCache](Clear-SoftpaqCache)
 
#>

function Get-SoftpaqMetadata {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Get%E2%80%90SoftpaqMetadata")]
  param(
    [ValidatePattern('^([Ss][Pp])*([0-9]{3,9})((\.[Ee][Xx][Ee]|\.[Cc][Vv][Aa])*)$')]
    [Parameter(Position = 0,Mandatory = $true)] [string]$Number,
    [Parameter(Position = 1,Mandatory = $false)] [string]$Url,
    [Parameter(Position = 2,Mandatory = $false)] [int]$MaxRetries = 0
  )

  $no = [int]$number.ToLower().TrimStart("sp").trimend(".exe").trimend('cva')
  [System.Net.ServicePointManager]::SecurityProtocol = Get-HPPrivateAllowedHttpsProtocols
  $loc = Get-HPPrivateItemUrl $no "cva" $url
  Get-HPPrivateReadINI -File $loc -Verbose:$VerbosePreference -MaxRetries $maxRetries
}


<#
.SYNOPSIS
    Retrieve SoftPaq (EXE) can retrieve a CVA or an alternate server.
 
.DESCRIPTION
    This function downloads a SoftPaq from a the default download server (ftp.hp.com) or an alternate server.
    When using the default location, the download is performed over HTTPS, otherwise the protocol is
  dictated by the URL parameter.
   
  If a SofPaq is either unavailable to download or has been obsoleted on the server, Get-Softpaq will display a warning that the SoftPaq could not be retrieved from ftp.hp.com.
   
  Get-Softpaq functionality is not supported in WinPE.
 
.PARAMETER Number
    The SoftPaq number for which to retrieve the metadata. Do not include prefix such as SP or extension such as .exe, specify the SoftPaq number only.
 
.PARAMETER SaveAs
    Provide a specific name for the saved SoftPaq, otherwise it is inferred based on the remote name or the SoftPaq metadata
    if -FriendlyName is specified.
 
.PARAMETER FriendlyName
    Create a friendly name for the downloaded SoftPaq, based on the SoftPaq number and title.
 
.PARAMETER Quiet
    Suppress non-errors such as download progress and other messages.
 
.PARAMETER Overwrite
    This parameter controls the overwrite behavior. Options may be "no" to not overwrite existing files,
    "yes" to force overwrite, and "skip" to skip existing files without an error. Default is 'no' if overwrite is
    not specified.
 
.PARAMETER Action
  Perform a specific action after download. The action may be "install" or "silentinstall".
  Silentinstall information is retrieved from the SoftPaq metadata (CVA) file.
 
.PARAMETER Extract
  Extracts files from a specified zipped archive file to a specified destination folder.
 
  Note:
    By default, files are extracted into a new sub-folder relative to the downloaded SoftPaq executable.
 
.PARAMETER DestinationPath
  Specifies the path to the folder in which you want to save extracted files.
  Enter the path to a folder, but do not specify a file name or file name extension.
 
  Note:
    By default, the files are extracted into a new sub-folder relative to the downloaded executable.
 
.PARAMETER Url
    specify an alternate location for the SoftPaq URL. This URL must be http, https, or ftp. The SoftPaqs are expected to be at the
    location pointed to by this URL. If not specified, ftp.hp.com is used via HTTPS protocol.
 
.PARAMETER KeepInvalidSigned
    this function performs an Authenticode signature check after a download, and deletes any
    downloaded file with invalid or missing signature. Use this flag to keep the file that failed the signature.
 
.PARAMETER MaxRetries
    Maximum number of retries allowed to obtain an exclusive lock to downloaded files. This is relevant only when
    files are downloaded into a shared directory and multiple processes may be reading or writing from the same
    location.
 
    Current default value is 10 retries, and each retry includes a 30 second pause, which means the maximum time the
  default value will wait for an exclusive logs is 300 seconds or 5 minutes.
 
.EXAMPLE
    Get-Softpaq -Number 1234
 
.EXAMPLE
    Get-Softpaq -Number 1234 -Extract -DestinationPath "c:\staging\drivers"
 
.LINK
    [Get-SoftpaqMetadata](Get-SoftpaqMetadata)
 
.LINK
    [Get-SoftpaqMetadataFile](Get-SoftpaqMetadataFile)
 
.LINK
    [Get-SoftpaqList](Get-SoftpaqList)
 
.LINK
    [Out-SoftpaqField](Out-SoftpaqField)
 
.LINK
    [Clear-SoftpaqCache](Clear-SoftpaqCache)
 
#>

function Get-Softpaq {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Get%E2%80%90Softpaq",DefaultParameterSetName = "DownloadParams")]
  param(
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 0,Mandatory = $true)]
    [string]$Number,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 1,Mandatory = $false)]
    [string]$SaveAs,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 2,Mandatory = $false)]
    [switch]$FriendlyName,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 3,Mandatory = $false)]
    [switch]$Quiet,

    [Parameter(ParameterSetName = "DownloadParams")]
    [ValidateSet("no","yes","skip")]
    [Parameter(Position = 4,Mandatory = $false)]
    [string]$Overwrite = "no",

    [Parameter(Position = 5,Mandatory = $false,ParameterSetName = "DownloadParams")]
    [Parameter(Position = 5,Mandatory = $false,ParameterSetName = "InstallParams")]
    [ValidateSet("install","silentinstall")]
    [string]$Action,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 6,Mandatory = $false)]
    [string]$Url,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 7,Mandatory = $false)]
    [switch]$KeepInvalidSigned,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 8,Mandatory = $false)]
    [int]$MaxRetries = 0,

    [Parameter(Mandatory = $false,ParameterSetName = "DownloadParams")]
    [Parameter(Mandatory = $false,ParameterSetName = "ExtractParams")]
    [switch]$Extract,

    [Parameter(Mandatory = $false,ParameterSetName = "DownloadParams")]
    [Parameter(Mandatory = $false,ParameterSetName = "ExtractParams")]
    [ValidatePattern('^[a-zA-Z]:\\')]
    [string]$DestinationPath
  )

  if ((Test-WinPE) -and ($action)) {
    throw [NotSupportedException]"Softpaq installation is not supported in WinPE"
  }

  [System.Net.ServicePointManager]::SecurityProtocol = Get-HPPrivateAllowedHttpsProtocols
  $no = [int]$number.ToLower().TrimStart("sp").trimend(".exe")

  if ($keepInvalidSigned.IsPresent) { $keepInvalid = $true }
  else { $keepInvalid = $false }

  if ($quiet.IsPresent) { $progress = -not $quiet }
  else { $progress = $true }

  $loc = Get-HPPrivateItemUrl -number $no -ext "exe" -url $url
  $target = $null
  $root = $null

  if ($friendlyName.IsPresent -or $action) {
    # get softpaq metadata
    try { $root = Get-SoftpaqMetadata $no -url $url -MaxRetries $maxRetries }
    catch {
      if ($progress -eq $true) {
        Write-Host -ForegroundColor Magenta "(Warning) Could not retrieve CVA file metadata for sp$no."
        Write-Host -ForegroundColor Magenta $_.Exception.Message
      }
    }
  }

  # build the filename
  if (!$saveAs) {
    if ($friendlyName.IsPresent)
    {
      Write-Verbose "Need to get CVA data to determine Friendly Name for Softpaq file"
      $target = getfriendlyFileName -number $no -info $root -Verbose:$VerbosePreference
      $target = "$target.exe"
    }

    else { $target = "sp$no.exe" }
  }
  else { $target = $saveAs }

  $targetFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($target)
  Write-Verbose $targetFile

  try
  {
    Invoke-HPPrivateDownloadFile -url $loc -Target $targetFile -progress $progress -NoClobber $overwrite -Verbose:$VerbosePreference -MaxRetries $maxRetries
  }
  catch
  {
    Write-Host -ForegroundColor Magenta "(Warning) Could not retrieve $loc."
    Write-Host -ForegroundColor Magenta $_.Exception.Message
    throw $_.Exception
  }

  # check digital signatures
  $signed = Get-HPPrivateCheckSignature -File $targetFile -Verbose:$VerbosePreference  -progress:(-not $Quiet.IsPresent)

  if ($signed -eq $false) {
    switch ($keepInvalid) {
      $true {
        if ($progress -eq $true) {
          Write-Host -ForegroundColor Magenta "(Warning): File $targetFile has invalid or missing signature"
          return
        }
      }
      $false {
        Invoke-HPPrivateSafeRemove -Path $targetFile -Verbose:$VerbosePreference
        throw [System.BadImageFormatException]"File $targetFile has invalid or missing signature and will be deleted."
        return
      }
    }
  }
  else {
    if ($progress -eq $true) {
      Write-Verbose "Digital signature is valid."
    }
  }

  # perform requested action
  if ($action -ne $null)
  {
    $PostInstallAction = if ($Extract.IsPresent) { "extract" } else { $action }
    Invoke-PostDownloadSoftpaqAction -downloadedFile $targetFile -Action $PostInstallAction -number $number -info $root -Destination $DestinationPath -Verbose:$VerbosePreference
  }
}

<#
.SYNOPSIS
    Retrieve softpaq metadata (CVA) can retrieve a CVA or an alternate server.
 
.DESCRIPTION
    Use this command to download a softpaq from a specified location. By default, the softpaq is retrieved
    from HP.COM via HTTPS.
 
.PARAMETER Number
    The softpaq number for which to retrieve the metadata. Do not include prefix such as SP or extension such as .exe.
 
.PARAMETER SaveAs
    Provide a specific name for the saved softpaq metadata, otherwise it is inferred based on the remote name or the metadata
    if -friendlyName is specified.
 
.PARAMETER FriendlyName
    Create a friendly name for the downloaded softpaq, based on the softpaq number and title.
 
.PARAMETER Quiet
    Suppress non-errors such as download progress and other messages.
 
.PARAMETER Overwrite
    This parameter controls the overwrite behavior. Options may be "no" to not overwrite existing files,
    "yes" to force overwrite, and "skip" to skip existing files without an error. Default is 'no' if overwrite is
    not specified.
 
.PARAMETER MaxRetries
    Maximum number of retries allowed to obtain an exclusive lock to downloaded files. This is relevant only when
    files are downloaded into a shared directory and multiple processes may be reading or writing from the same
    location.
 
    Current default value is 10 retries, and each retry includes a 30 second pause, which means the maximum time the
  default value will wait for an exclusive logs is 300 seconds or 5 minutes.
 
.PARAMETER url
    An alternate URL where to look for the softpaq
 
.EXAMPLE
    Get-SoftpaqMetadataFile 1234
 
.LINK
    [Get-SoftpaqMetadata](Get-SoftpaqMetadata)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Get-SoftpaqList](Get-SoftpaqList)
 
.LINK
    [Out-SoftpaqField](Out-SoftpaqField)
 
.LINK
    [Clear-SoftpaqCache](Clear-SoftpaqCache)
 
#>

function Get-SoftpaqMetadataFile {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Get%E2%80%90SoftpaqMetadataFile")]
  param(
    [ValidatePattern('^([Ss][Pp])*([0-9]{3,9})((\.[Ee][Xx][Ee]|\.[Cc][Vv][Aa])*)$')]
    [Parameter(Position = 0,Mandatory = $true)]
    [string]$Number,
    [Parameter(Position = 1,Mandatory = $false)]
    [string]$SaveAs,
    [Parameter(Position = 2,Mandatory = $false)]
    [switch]$FriendlyName,
    [Parameter(Position = 3,Mandatory = $false)]
    [switch]$Quiet,
    [ValidateSet("No","Yes","Skip")]
    [Parameter(Position = 4,Mandatory = $false)]
    [string]$Overwrite = "No",
    [Parameter(Position = 5,Mandatory = $false)]
    [string]$Url,
    [Parameter(Position = 6,Mandatory = $false)]
    [int]$MaxRetries = 0
  )

  [System.Net.ServicePointManager]::SecurityProtocol = Get-HPPrivateAllowedHttpsProtocols
  $no = [int]$number.ToLower().TrimStart("sp").trimend(".exe").trimend('cva')

  if ($quiet.IsPresent) { $progress = -not $quiet }
  else { $progress = $true }

  $loc = Get-HPPrivateItemUrl -number $no -ext "cva" -url $url

  $target = $null

  # get softpaq metadata. We don't need this step unless we get friendly name
  if ($friendlyName.IsPresent) {
    Write-Verbose "Need to get CVA data to determine Friendly Name for CVA file"
    try { $root = Get-SoftpaqMetadata $number -url $url -MaxRetries $maxRetries }
    catch {
      if ($progress -eq $true) {
        Write-Host -ForegroundColor Magenta "(Warning) Could not retrieve CVA file metadata"
        Write-Host -ForegroundColor Magenta $_.Exception.Message
      }
      $root = $null
    }
  }

  # build the filename
  if (!$saveAs) {
    if ($friendlyName.IsPresent) {
      Write-Verbose "Need to get CVA data to determine Friendly Name for CVA file"
      $target = getfriendlyFileName -number $no -info $root -Verbose:$VerbosePreference
      $target = "$target.cva"
    }
    else { $target = "sp$no.cva" }
  }
  else { $target = $saveAs }

  # download the file
  $targetFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($target)
  Invoke-HPPrivateDownloadFile -url $loc -Target $targetFile -progress $progress -NoClobber $overwrite -Verbose:$VerbosePreference -MaxRetries $maxRetries -skipSignatureCheck
}

<#
.SYNOPSIS
    Filter a loaded softpaq metadata
 
.DESCRIPTION
    Extract the specified field from the softpaq metadata. Some of the currently supported fields are:
 
    * Title
    * Description
    * SilentInstall
    * Number
    * Platforms
    * PlatformIDs
    * Version
    * SoftPaqSHA256
    * SoftPaqMD5
 
.PARAMETER Field
    The predefined filter to retrieve
 
.PARAMETER InputObject
    data coming from the pipeline
 
.EXAMPLE
    $mysoftpaq | Out-SoftpaqField -Field Title
 
 
.LINK
    [Get-SoftpaqMetadata](Get-SoftpaqMetadata)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Get-SoftpaqList](Get-SoftpaqList)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Clear-SoftpaqCache](Clear-SoftpaqCache)
 
 
#>

function Out-SoftpaqField {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Out%E2%80%90SoftpaqField")]
  param(
    [ValidateSet("Install","SilentInstall","Title","Description","Number","Platforms","PlatformIDs","SoftPaqSHA256","SoftPaqMD5","Version")]
    [Parameter(Mandatory = $True)]
    [string]$Field,

    [ValidateNotNullOrEmpty()]
    [Parameter(ValueFromPipeline = $True,Mandatory = $True)]
    [Alias('In')]
    $InputObject
  )

  begin {
    if (!$mapper.contains($field)) {
      throw [InvalidOperationException]"Field '$field' is not supported as a filter"
    }
  }
  process
  {
    $result = descendNodesAndGet $InputObject -Field $field
    if ($mapper[$field] -match "%KeyValues\(.*\)$") {

      $pattern = $mapper[$field] -match "\((.*)\)"
      if ($pattern[0]) {

        # Need to narrow it down to PlatformIDs otherwise Platforms will be shown in UpperCase too.
        if ($Field -eq "PlatformIDs") {
          $result = $result[$result.keys -match $matches[1]].ToUpper() | Get-Unique
          return $result -replace "^0X",''
        }
        else {
          return $result[$result.keys -match $matches[1]] | Get-Unique
        }
      }
    }
    return $result
  }
  end {}
}

<#
.SYNOPSIS
    Clear the softpaq cache.
 
.DESCRIPTION
 
    Clear the cache used for downloading softpaq database files.
 
    This is normally not needed as part of normal operation, the cache doesn't grow significantly over time, and is also cleared
    by normal operations that flush the user's temporary directory.
 
    The function is only intended as a debugging function.
 
 
 
.EXAMPLE
    Clear-SoftpaqCache
 
.PARAMETER cacheDir
    Custom location for caching data files. If not specified, the user-specific TEMP directory is used.
 
 
.LINK
    [Get-SoftpaqMetadata](Get-SoftpaqMetadata)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Get-SoftpaqList](Get-SoftpaqList)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Out-SoftpaqField](Out-SoftpaqField)
 
.NOTES
    This command removes the cached files from the user temporary directory. It cannot be used to clear the cache
    when the data files are stored inside a repository structure. Custom cache locations (other than the default)
    must be specified via the cacheDir folder.
 
#>

function Clear-SoftpaqCache {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Clear%E2%80%90SoftpaqCache")]
  param(
    [Parameter(Mandatory = $false)]
    [System.IO.DirectoryInfo]$CacheDir
  )
  $cacheDir = Get-HPPrivateCacheDirPath ($cacheDir)
  Invoke-HPPrivateSafeRemove -Path $cacheDir -Recurse
}

<#
.SYNOPSIS
    Get a list of SoftPaqs for a platform
 
.DESCRIPTION
  This function gets a list of latest SoftPaqs for a specified platform ID, or the current computer.
   
  Get-SoftpaqList functionality is not supported in WinPE.
 
.PARAMETER Platform
    The platform ID for which to retrieve the list of SoftPaqs. If not available, the current platform ID is used.
 
.PARAMETER Bitness
    the platform bitness (32 or 64). If not available, the current platform bitness is used.
 
.PARAMETER Os
    filter for the specified OS. The OS may be one of win7, win8, win8.1, win10. If not specified, current platform OS is used.
 
.PARAMETER OsVer
    filter for the specified OS Version. Applies to Win10 only. This is a string value, specifying the target OS Version (e.g. 1709, 1803, 21H1 etc). If the parameter is not specified, current operating system version
    will be assumed, which may not be what is intended. For windows versions other than windows 10, this is silently ignored.
 
.PARAMETER Category
    The category field filters to a specific category of SoftPaqs. It must be one (or more) of "Bios", "Firmware", "Driver", "Software", "OS", "Manageability", "Diagnostic", "Utility", "Driverpack", "Dock", "UWPPack".
 
.PARAMETER ReleaseType
    filter to specified release type. The release type must be one (or more) of "Critical", "Recommended", "Routine".
 
.PARAMETER ReferenceUrl
    specify an alternate location for the HP Image Assistant(HPIA) Reference files. This URL must be http, https, or ftp. The Reference files are expected to be at the location pointed to by
    this URL inside a directory named after the platform ID you want a SoftPaq list for. If not specified, ftp.hp.com is used via HTTPS protocol.
 
    For example, If you want to point to 83b2 Win10 OSVer 2009 reference files, Get-SoftpaqList will try to find them in this directory structure: $ReferenceUrl/83b2/83b2_64_10.0.2009.cab
 
.PARAMETER SoftpaqUrl
    specify an alternate location for the SoftPaq URL. This URL must be http, https, or ftp. The SoftPaqs are expected to be at the location pointed to by
    this URL. If not specified, ftp.hp.com is used via HTTPS protocol.
 
.PARAMETER Quiet
    Suppress non-error progress messages
 
.PARAMETER Download
    download matching SoftPaqs
 
.PARAMETER DownloadMetadata
    also download CVA files (metadata) for matching SoftPaqs
 
.PARAMETER DownloadNotes
    also download note files (human readable info files) for matching SoftPaqs
 
.PARAMETER DownloadDirectory
    specify a directory for the downloaded files
 
.PARAMETER FriendlyName
    if specified, retrieve the SoftPaq metadata and create a friendly file name based on the SoftPaq title. Applies if -download is specified.
 
.PARAMETER Overwrite
    This parameter controls the overwrite behavior. Options may be "no" to not overwrite existing files,
    "yes" to force overwrite, and "skip" to skip existing files without an error. Default is 'no' if overwrite is
    not specified.
 
.PARAMETER Format
    Display results in a specified format (Json, XML, or CSV). If not specified, results are returned as PowerShell objects
 
.PARAMETER Characteristic
    Specify additional filter characteristics for the softpaq list. The characteristic must be one (or more) of "SSM", "DPB", "UWP".
 
.PARAMETER CacheDir
    Custom location for caching data files. If not specified, the user-specific TEMP directory is used.
 
.PARAMETER MaxRetries
    Maximum number of retries allowed to obtain an exclusive lock to downloaded files. This is relevant only when
    files are downloaded into a shared directory and multiple processes may be reading or writing from the same
    location.
 
    Current default value is 10 retries, and each retry includes a 30 second pause, which means the maximum time the
  default value will wait for an exclusive logs is 300 seconds or 5 minutes.
 
.PARAMETER PreferLTSC
    if specified and if data file exists, retrieves the LTSB/LTSC Reference file for the entered Platform.
  If data file doesn't exists- falls back to regular Reference file for that platform.
 
.EXAMPLE
    Get-SoftpaqList -Download
.EXAMPLE
    Get-SoftpaqList -Bitness 64 -Os win10 -OsVer 1903
.EXAMPLE
    Get-SoftpaqList -Platform 83b2 -Os win10 -OsVer "21H1"
.EXAMPLE
    Get-SoftpaqList -Platform 8444 -Category Diagnostic -Format json
.EXAMPLE
    Get-SoftpaqList -Category Driverpack
.EXAMPLE
    Get-SoftpaqList -ReleaseType Critical -Characteristic SSM
.EXAMPLE
    Get-SoftpaqList -Platform 83b2 -Category Dock,Firmware -ReleaseType Routine,Critical
.EXAMPLE
    Get-SoftpaqList -Platform 2216 -Category Driverpack -Os win10 -OsVer 1607 -PreferLTSC
 
.LINK
    [Get-SoftpaqMetadata](Get-SoftpaqMetadata)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Clear-SoftpaqCache](Clear-SoftpaqCache)
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
  [Out-SoftpaqField](Out-SoftpaqField)
   
.NOTES
  The response is a record set composed of zero or more SoftPaq records. The definition of a record is as follows:
 
  | Field | Description |
  |---------------|-------------|
  | Id | The SoftPaq identifier |
  | Name | The SoftPaq name (title) |
  | Category | The SoftPaq category |
  | Version | The SoftPaq version |
  | Vendor | The author of the SoftPaq |
  | ReleaseType | The SoftPaq release type |
  | SSM | This flag indicates this SoftPaq support unattended silent install |
  | DPB | This flag indicates this SoftPaq is included in driver pack builds |
  | Url | The SoftPaq download URL |
  | ReleaseNotes | The URL to a human-readable rendering of the SoftPaq release notes |
  | Metadata | The URL to the SoftPaq metadata (CVA) file |
  | MD5 | (where available) The MD5 value for this softpaq |
  | Size | The SoftPaq size, in bytes |
  | ReleaseDate | The date the SoftPaq was published |
  | UWP | (where available) This flag indicates this SoftPaq contains Universal Windows Platform applications |
 
 
#>

function Get-SoftpaqList {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Get%E2%80%90SoftpaqList",DefaultParameterSetName = "ViewParams")]
  param(

    [ValidatePattern("^[a-fA-F0-9]{4}$")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 0,Mandatory = $false,ParameterSetName = "ViewParams")] [string]$Platform,

    [ValidateSet(32,64)]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 1,Mandatory = $false,ParameterSetName = "ViewParams")] [int]$Bitness,

    [ValidateSet($null,"win7","win8","win8.1","win81","win10")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 2,Mandatory = $false,ParameterSetName = "ViewParams")] [string]$Os,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 3,Mandatory = $false,ParameterSetName = "ViewParams")] [string]$OsVer,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Alias('Url')]
    [Parameter(Position = 4,Mandatory = $false,ParameterSetName = "ViewParams")] [string]$ReferenceUrl = "https://hpia.hpcloud.hp.com/ref",

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 5,Mandatory = $false,ParameterSetName = "ViewParams")] [switch]$Quiet,

    [Parameter(ParameterSetName = "DownloadParams")]
    [ValidateSet("XML","Json","CSV")]
    [Parameter(Position = 6,ParameterSetName = "ViewParams")] [string]$Format,

    [Parameter(Position = 7,ParameterSetName = "DownloadParams")] [string]$DownloadDirectory,

    [Alias("downloadSoftpaq","downloadPackage")]
    [Parameter(Position = 8,ParameterSetName = "DownloadParams")] [switch]$Download,

    [Alias("downloadCva")]
    [Parameter(Position = 9,ParameterSetName = "DownloadParams")] [switch]$DownloadMetadata,
    [Parameter(Position = 10,ParameterSetName = "DownloadParams")] [switch]$DownloadNotes,
    [Parameter(Position = 11,ParameterSetName = "DownloadParams")] [switch]$FriendlyName,

    [ValidateSet("No","Yes","Skip")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 12,Mandatory = $false,ParameterSetName = "ViewParams")] [string]$Overwrite = "No",


    [ValidateSet("BIOS","Firmware","Driver","Software","OS","Manageability","Diagnostic","Utility","Driverpack","Dock","UWPPack")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 13,ParameterSetName = "ViewParams")] [string[]]$Category = $null,


    [ValidateSet("Critical","Recommended","Routine")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 14,ParameterSetName = "ViewParams")] [string[]]$ReleaseType = $null,


    [ValidateSet("SSM","DPB","UWP")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 15,ParameterSetName = "ViewParams")] [string[]]$Characteristic = $null,


    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 16,ParameterSetName = "ViewParams")] [System.IO.DirectoryInfo]$CacheDir,

    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 17,Mandatory = $false,ParameterSetName = "ViewParams")] [int]$MaxRetries = 0,

    [Alias("PreferLTSB")]
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 18,Mandatory = $false,ParameterSetName = "ViewParams")] [switch]$PreferLTSC,
    
    [Parameter(ParameterSetName = "DownloadParams")]
    [Parameter(Position = 19,Mandatory = $false,ParameterSetName = "ViewParams")] [string]$SoftpaqUrl    
  )

  if (Test-WinPE) {
    throw [NotSupportedException]"This operation is not supported in WinPE"
  }

  [System.Net.ServicePointManager]::SecurityProtocol = Get-HPPrivateAllowedHttpsProtocols
  $ver = ""
  $progress = $true
  $cacheDir = Get-HPPrivateCacheDirPath ($cacheDir)

  if ($quiet.IsPresent) { $progress = -not $quiet }
  if (-not $platform) { $platform = Get-HPDeviceProductID }
  $platform = $platform.ToLower()
  if ($OsVer) { $OsVer = $OsVer.ToLower() }

  if (!$bitness) { if ([environment]::Is64BitOperatingSystem -eq $true) { $bitness = 64 } else { $bitness = 32 } }
  if (!$os)
  {
    switch ([string][System.Environment]::OSVersion.Version.Major + "." + [string][System.Environment]::OSVersion.Version.Minor) {
      "10.0" { $os = "win10" }
      "6.3" { $os = "win81" }
      "6.2" { $os = "win8" }
      "6.1" { $os = "win7" }
    }
  }


  if(([System.Environment]::OSVersion.Version.Major -eq 10) -and $OsVer) {

    try {
      # try converting OsVer to int
      $OSVer = [Int]$OsVer

      if($OSVer -gt 2009 -or $OSVer -lt 1507) {
        throw "Unsupported operating system version"
      }
    }
    catch {
      if (!($OSVer -match '[0-9]{2}[hH][0-9]')) {
        throw "Unsupported operating system version"
      }
    }
  }

  # determine OSVer for Win10 if OSVer is not passed
  if (([System.Environment]::OSVersion.Version.Major -eq 10) -and (!$osver))
  {
    Write-Verbose "need to determine OSVer"
    $osver = GetCurrentOSVer
  }

  switch ($os)
  {
    "win10" { $ver = "10.0." + $osver.ToString() }
    "win81" { $ver = "6.3" }
    "win8.1" { $ver = "6.3" }
    "win8" { $ver = "6.2" }
    "win7" { $ver = "6.1" }
    default { throw [NotSupportedException]"Unsupported operating system: " + $_ }
  }

  $fn = "$($platform)_$($bitness)_$($ver)"
  #Write-Host -ForegroundColor Magenta $fn
  $result = $null
  $LTSCExists = $false
  $ReferenceFallbackUrL = "https://ftp.hp.com/pub/caps-softpaq/cmit/imagepal/ref"

  if ($PreferLTSC.IsPresent) {
    $qurl = "$ReferenceUrl/$platform/$fn.e.cab"
    $qfile = Get-HPPrivateTemporaryFileName -FileName "$fn.e.cab" -cacheDir $cacheDir
    $downloadedFile = "$qfile.dir\$fn.e.xml"
    $try_on_ftp = $false
    try {
      $result = Test-HPPrivateIsDownloadNeeded -url $qurl -File $qfile -Verbose:$VerbosePreference
      if ($result[1] -eq $true) {
        Write-Verbose "Trying to download $qurl from AWS Server..."
      }
      $LTSCExists = $true
    }
    catch {
      $try_on_ftp = $true
    }

    if ($try_on_ftp) {
      try {
        Write-Verbose "$qurl not found on AWS Server. Trying to download it from FTP Server..."
        $qurl = "$ReferenceFallbackUrl/$platform/$fn.e.cab"
        $result = Test-HPPrivateIsDownloadNeeded -url $qurl -File $qfile -Verbose:$VerbosePreference
        if ($result[1] -eq $true) {
          $LTSCExists = $true
        }
      }
      catch {
        if (-not $quiet -or $result[1] -eq $false) {
          Write-Host -ForegroundColor Magenta "LTSB/LTSC data file doesn't exists for platform $platform ($os $osver)"
          Write-Host -ForegroundColor Cyan "Getting the regular (non LTSB/LTSC) data file for this platform"
        }
      }
    }
  }

  # LTSB(C) file doesn't exists, fall back to regular Ref file
  if ((-not $PreferLTSC.IsPresent) -or ($PreferLTSC.IsPresent -and ($LTSCExists -eq $false))) {
    $qurl = "$ReferenceUrl/$platform/$fn.cab"
    $qfile = Get-HPPrivateTemporaryFileName -FileName "$fn.cab" -cacheDir $cacheDir
    $downloadedFile = "$qfile.dir\$fn.xml"
    $try_on_ftp = $false
    try {
      $result = Test-HPPrivateIsDownloadNeeded -url $qurl -File $qfile -Verbose:$VerbosePreference
      if ($result[1] -eq $true) {
        Write-Verbose "Trying to download $qurl from AWS Server..."
      }
    }
    catch {
      $try_on_ftp = $true
    }

    if ($try_on_ftp) {
      try {
        Write-Verbose "$qurl not found on AWS Server. Trying to download it from FTP Server..."
        $qurl = "$ReferenceFallbackUrl/$platform/$fn.cab"
        $result = Test-HPPrivateIsDownloadNeeded -url $qurl -File $qfile -Verbose:$VerbosePreference
      }
      catch { 
        if (-not $quiet -or $result[1] -eq $false) {
          Write-Host -ForegroundColor Magenta $_.Exception.Message
        }
        throw [System.Net.WebException]"Could not find a data file for this platform."
      }
    }
  }

  if ($result[1] -eq $true) {
    Write-Verbose "Cleaning cached data and downloading the data file."
    Invoke-HPPrivateDeleteCachedItem -cab $qfile
    Invoke-HPPrivateDownloadFile -url $qurl -Target $qfile -progress $progress -NoClobber $overwrite -Verbose:$VerbosePreference -MaxRetries $maxRetries
    (Get-Item $qfile).CreationTime = ($result[0])
    (Get-Item $qfile).LastWriteTime = ($result[0])
  }

  # Need to make sure that the expanded data file exists and is not corrupted.
  # Otherwise, expand the cab file.
  if (-not (Test-Path $downloadedFile) -or (-not (Test-HPPrivateIsValidXmlFile -File $downloadedFile)))
  {
    Write-Verbose "Extracting the data file, looking for $downloadedFile."
    $file = Invoke-HPPrivateExpandCAB -cab $qfile -expectedFile $downloadedFile
  }

  Write-Verbose "Reading XML document $downloadedFile"
  [xml]$data = Get-Content $downloadedFile
  Write-Verbose "Parsing the document"

  $d = Select-Xml -Xml $data -XPath "//ImagePal/Solutions/UpdateInfo"

  $results = $d.Node | ForEach-Object {
    if (($null -ne $releaseType) -and ($_.releaseType -notin $releaseType)) { return }
    if (-not (matchCategory -cat $_.category -allowed $category -EQ $true)) { return }
    if ("ContentTypes" -in $_.PSObject.Properties.Name) { $ContentTypes = $_.ContentTypes } else { $ContentTypes = $null }
    if (($null -ne $characteristic) -and (-not (matchAllCharacteristic $characteristic -SSM $_.SSMCompliant -DPB $_.DPBCompliant -UWP $ContentTypes))) { return }

    $pso = [pscustomobject]@{
      Id = $_.Id
      Name = $_.Name
      category = $_.category
      Version = $_.Version.TrimStart("0.")
      Vendor = $_.Vendor
      releaseType = $_.releaseType
      SSM = $_.SSMCompliant
      DPB = $_.DPBCompliant
      Url = $_.Url
      ReleaseNotes = $_.ReleaseNotesUrl
      Metadata = $_.CvaUrl
      MD5 = $_.MD5
      Size = $_.Size
      ReleaseDate = $_.DateReleased
      UWP = $(if ("ContentTypes" -in $_.PSObject.Properties.Name) { $true } else { $false })
    }
    $pso



    if ($download.IsPresent) {
      [int]$id = $pso.Id.ToLower().replace("sp","")
      if ($friendlyName.IsPresent) {
        Write-Verbose "Need to get CVA data to determine Friendly Name for download file"
        $target = getfriendlyFileName -number $pso.Id.ToLower().TrimStart("sp") -From $pso.Name -Verbose:$VerbosePreference
      }
      else { $target = $pso.Id }

      if ($downloadDirectory) { $target = "$downloadDirectory\$target" }
      else {
        $cwd = Convert-Path .
        $target = "$cwd\$target"
      }

      if ($downloadMetadata.IsPresent)
      {
        $loc = Get-HPPrivateItemUrl -Number $Id -Ext "cva" -Url $SoftpaqUrl
        Invoke-HPPrivateDownloadFile -url $loc -Target "$target.cva" -progress $progress -NoClobber $overwrite -Verbose:$VerbosePreference -skipSignatureCheck -MaxRetries $maxRetries
      }

      $loc = Get-HPPrivateItemUrl -Number $Id -Ext "exe" -Url $SoftpaqUrl
      
      Invoke-HPPrivateDownloadFile -url $loc -Target "$target.exe" -progress $progress -NoClobber $overwrite -Verbose:$VerbosePreference -MaxRetries $maxRetries

      if ($downloadNotes.IsPresent)
      {
        $loc = Get-HPPrivateItemUrl -Number $Id -Ext "html" -Url $SoftpaqUrl
        Invoke-HPPrivateDownloadFile -url $loc -Target "$target.htm" -progress $progress -NoClobber $overwrite -Verbose:$VerbosePreference -skipSignatureCheck -MaxRetries $maxRetries
      }
    }
  }

  $result = $results | Select-Object * -Unique
  switch ($format)
  {
    "xml" { $result | ConvertTo-Xml -As String }
    "json" { $result | ConvertTo-Json }
    "csv" { $result | ConvertTo-Csv -NoTypeInformation }
    default { return $result }
  }
}

<#
.SYNOPSIS
  Install the latest version of HP Image Assistant [HPIA](https://ftp.hp.com/pub/caps-softpaq/cmit/HPIA.html)
 
.DESCRIPTION
  This function figures out the latest version of HPIA and downloads the SoftPaq. If -Extract is not used, the SoftPaq is only downloaded.
 
.PARAMETER Extract
  Extracts SoftPaq content to a specified destination folder.
 
  Note:
    By default, files are extracted into a new sub-folder relative to the downloaded SoftPaq executable.
 
.PARAMETER DestinationPath
  Specifies the path to the folder in which you want to save extracted files.
  Enter the path to a folder, but do not specify a file name or file name extension.
 
  Note:
    By default, the files are extracted into a new sub-folder relative to the downloaded executable.
 
.PARAMETER Source
  This parameter is currently reserved for internal use only.
 
.PARAMETER CacheDir
    Custom location for caching data files. If not specified, the user-specific TEMP directory is used.
 
.PARAMETER MaxRetries
    Maximum number of retries allowed to obtain an exclusive lock to downloaded files. This is relevant only when
    files are downloaded into a shared directory and multiple processes may be reading or writing from the same
    location.
 
    Current default value is 10 retries, and each retry includes a 30 second pause, which means the maximum time the
  default value will wait for an exclusive logs is 300 seconds or 5 minutes.
 
.PARAMETER Quiet
  Suppress non-errors such as download progress and other messages.
 
.EXAMPLE
    Install-HPImageAssistant
 
.EXAMPLE
    Install-HPImageAssistant -Quiet
 
.EXAMPLE
    Install-HPImageAssistant -Extract -DestinationPath "c:\staging\hpia"
 
.LINK
    [Get-Softpaq](Get-Softpaq)
 
.LINK
    [Get-SoftpaqMetadataFile](Get-SoftpaqMetadataFile)
 
.LINK
    [Get-SoftpaqList](Get-SoftpaqList)
 
.LINK
    [Clear-SoftpaqCache](Clear-SoftpaqCache)
 
#>

function Install-HPImageAssistant {
  [CmdletBinding(HelpUri = "https://developers.hp.com/hp-client-management/doc/Install%E2%80%90HPImageAssistant")]
  param (
    [Parameter (Position = 0, Mandatory = $false, ParameterSetName = "ExtractParams")]
    [switch] $Extract,

    [Parameter(Position = 1, Mandatory = $false, ParameterSetName = "ExtractParams")] 
    [ValidatePattern('^[a-zA-Z]:\\')]
    [string] $DestinationPath,

    [Parameter(Position = 2, Mandatory = $false)]
    [System.IO.DirectoryInfo] $CacheDir,

    [Parameter(Position = 3, Mandatory = $false)] 
    [int] $MaxRetries = 0,

    [Parameter(Position = 4, Mandatory = $false)]
    [string] $Source = "https://hpia.hpcloud.hp.com/HPIAMsg.cab",

    [Parameter(Position = 5, Mandatory = $false)]
    [switch] $Quiet
  )
  
  if ($quiet.IsPresent) { $progress = -not $quiet }
  else { $progress = $true }

  $cacheDir = Get-HPPrivateCacheDirPath ($cacheDir)
  
  $fallbackSource = "https://ftp.hp.com/pub/caps-softpaq/cmit/imagepal/HPIAMsg.cab" 
  
  $sourceFile = Get-HPPrivateTemporaryFileName -FileName "HPIAMsg.cab" -cacheDir $cacheDir
  $downloadedFile = "$sourceFile.dir\HPIAMsg.xml"

  $try_on_ftp = $false
  try {
    $result = Test-HPPrivateIsDownloadNeeded -url $source -File $sourceFile -Verbose:$VerbosePreference
    if ($result[1] -eq $true) {
      Write-Verbose "Trying to download $source from AWS Server..."
    }
  }
  catch {
    $try_on_ftp = $true
  }

  if ($try_on_ftp) {
    try {
      Write-Verbose "$source not found on AWS Server. Trying to download it from FTP Server..."
      $source = $fallbackSource
      $result = Test-HPPrivateIsDownloadNeeded -url $source -File $sourceFile -Verbose:$VerbosePreference
      if ($result[1] -eq $true) {
        Write-Verbose "Trying to download $source from FTP Server..."
      }
    }
    catch {
      if ($result[1] -eq $false) {
        Write-Host -ForegroundColor Magenta "data file not found"
      }
    }
  }

  if ($result[1] -eq $true) {
    Write-Verbose "Cleaning cached data and downloading the data file."
    Invoke-HPPrivateDeleteCachedItem -cab $sourceFile
    Invoke-HPPrivateDownloadFile -url $source -Target $sourceFile -progress $progress -Verbose:$VerbosePreference -MaxRetries $maxRetries
  }

  Write-Verbose "Downloaded file is : $downloadedFile"
  # Need to make sure that the expanded data file exists and is not corrupted.
  # Otherwise, expand the cab file.
  if (-not (Test-Path $downloadedFile) -or (-not (Test-HPPrivateIsValidXmlFile -File $downloadedFile)))
  {
    Write-Verbose "Extracting the data file, looking for $downloadedFile."
    $file = Invoke-HPPrivateExpandCAB -cab $sourceFile -expectedFile $downloadedFile
    Write-Verbose $file 
  }

  Write-Verbose "Reading XML document $downloadedFile"
  [xml]$data = Get-Content $downloadedFile
  Write-Verbose "Parsing the document"

  # Getting the SoftPaq information
  $SoftpaqVersion = $data.ImagePal.HPIALatest.Version
  $SoftpaqUrl = $data.ImagePal.HPIALatest.SoftpaqURL
  $Softpaq = $SoftpaqUrl.Split('/')[-1]
  $SoftpaqExtractedFolderName = $Softpaq.ToLower().trimend(".exe")

  $TargetFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Softpaq)

  Write-Verbose "SoftPaq Version: $SoftpaqVersion"
  Write-Verbose "SoftPaq URL: $SoftpaqUrl"

  $params = @{
    URL        = $SoftpaqUrl
    Target     = $TargetFile
    MaxRetries = $MaxRetries
    Progress   = $progress
  }

  try {
    Invoke-HPPrivateDownloadFile @params
    Write-Verbose "Successfully downloaded SoftPaq at $TargetFile"
    # if Extract and Destination location is specified, proceed to extract the SoftPaq
    if ($Extract) {
      if (!$DestinationPath) {
        Invoke-PostDownloadSoftpaqAction -downloadedFile $TargetFile -Action "Extract"
        $cwd = Get-Location
        Write-Verbose "Successfully extracted SoftPaq at $cwd\$SoftpaqExtractedFolderName"
      }
      else {
        Invoke-PostDownloadSoftpaqAction -downloadedFile $TargetFile -Action "Extract" -Destination $DestinationPath
        Write-Verbose "Successfully extracted SoftPaq at $DestinationPath"
      }
    }
    Write-Verbose "Success"
  }
  catch {
    if (-not $Quiet) {
      Write-Host -ForegroundColor Magenta $_.Exception.Message
    }
    throw $_.Exception
  }
}



# private functionality below

function matchCategory ([string]$cat,[string[]]$allowed)
{
  if ($allowed -eq $null) { return $true }
  if ($cat.startsWith("Driver") -eq $true) { return $allowed -eq "driver" }
  if ($cat.startsWith("Operating System -") -eq $true) { return $allowed -eq "os" }
  if ($cat.startsWith("Manageability - Driver Pack") -eq $true) { return $allowed -eq "driverpack" }
  if ($cat.startsWith("Manageability - UWP Pack") -eq $true) { return $allowed -eq "UWPPack" }
  if ($cat.startsWith("Manageability -") -eq $true) { return $allowed -eq "manageability" }
  if ($cat.startsWith("Utility -") -eq $true) { return $allowed -eq "utility" }
  if (($cat.startsWith("Dock -") -eq $true) -or ($cat -eq "Docks")) { return $allowed -eq "dock" }
  if (($cat -eq "BIOS") -or ($cat.startsWith("BIOS -") -eq $true)) { return $allowed -eq "BIOS" }
  if ($cat -eq "firmware") { return $allowed -eq "firmware" }
  if ($cat -eq "diagnostic") { return $allowed -eq "diagnostic" }
  else {
    return $allowed -eq "software"
  }
  return $false
}

function matchAllCharacteristic ([string[]]$targetedCharacteristic,[string]$SSM,[string]$DPB,[string]$UWP)
{
  if ($targetedCharacteristic -eq $null) { return $true }
  if ($targetedCharacteristic.Count -eq 0) { return $true }

  $ContainsAllCharacteristic = $true

  foreach ($characteristic in $targetedCharacteristic)
  {
    switch ($characteristic.Trim().ToLower()) {
      "ssm"
      {
        if ($SSM.Trim().ToLower() -eq "false") { $ContainsAllCharacteristic = $false }
      }
      "dpb"
      {
        if ($DPB.Trim().ToLower() -eq "false") { $ContainsAllCharacteristic = $false }
      }
      "uwp"
      {
        if ($UWP.Trim().ToLower() -ne "uwp") { $ContainsAllCharacteristic = $false }
      }
    }
  }
  return $ContainsAllCharacteristic
}



function Release-Ref ($ref) {
  [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) | Out-Null
  [System.GC]::Collect()
  [System.GC]::WaitForPendingFinalizers()
}

# create a friendly name from softpaq metadata (CVA)
function getfriendlyFileName
{
  [CmdletBinding()]
  param(
    [int]$number,
    $info,
    [string]$from
  )

  try {
    $title = "sp$number"

    #if title was passed in, we use it
    if ($from) { $title = $from }

    #else if object was passed in, we use it
    elseif ($info -ne $null) { $title = ($info | Out-SoftpaqField Title) }

    #else use a default
    else { $title = "(No description available)" }

    $pass1 = removeInvalidCharacters $title
    $pass2 = $pass1.Trim()
    $pass3 = $pass2 -replace ('\s+','_')
    return $number.ToString("sp######") + "-" + $pass3
  }
  catch {
    Write-Host -ForegroundColor Magenta "Could not determine friendly name, using softpaq number."
    Write-Host -ForegroundColor Magenta $_.Exception.Message
    return "sp$number"
  }
}

# remove invalid characters from a filename
function removeInvalidCharacters ([string]$Name) {
  $invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
  $re = "[{0}]" -f [regex]::Escape($invalidChars)
  return ($Name -replace $re)
}

#shortcuts to various sections of CVA file
$mapper = @{
  "Install" = "Install Execution|Install";
  "SilentInstall" = "Install Execution|SilentInstall";
  "Number" = "Softpaq|SoftpaqNumber";
  "Title" = "Software Title|%lang";
  "Description" = "%lang.Software Description|_body";
  "Platforms" = "System Information|%KeyValues(^SysName.*$)";
  "PlatformIDs" = "System Information|%KeyValues(^SysId.*$)";
  "SoftPaqSHA256" = "Softpaq|SoftPaqSHA256";
  "SoftPaqMD5" = "Softpaq|SoftPaqMD5";
  "Version" = "General|VendorVersion";
};

#ISO to CVA language mapper
$lang_mapper = @{
  "en" = "us";
};


# navigate a CVA structure
function descendNodesAndGet ($root,$field,$lang = "en")
{
  $f1 = $mapper[$field].Replace("%lang",$lang_mapper[$lang])
  $f = $f1.Split("|")
  $node = $root

  foreach ($c in $f) {
    if ($c -match "^%KeyValues\(.*\)$") { return $node }
    if ($c -match "^%Keys\(.*\)$") { return $node }
    $node = $node[$c]
  }
  $node
}


# SIG # Begin signature block
# MIIakQYJKoZIhvcNAQcCoIIagjCCGn4CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3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