Functions/ConvertTo-CsvObject.ps1

<#
.SYNOPSIS
    This function converts a CSV string to a CSV object.
.DESCRIPTION
    This function takes in a CSV representation as a string and returns a custom object with
    properties that correspond to the CSV.
.PARAMETER csvString
    The string containing the CSV representation.
#>

function ConvertTo-CsvObject {
    [CmdletBinding()]
    [OutputType([Object[]])]
    param (
        # The string containing the CSV representation.
        [Parameter(Mandatory=$true)]
        [String]$csvString,

        # If this parameter is set, the names of the headers will be trimmed.
        [Parameter(Mandatory=$false)]
        [ValidateNotNull()]
        [Switch]$trimHeaders = [Switch]::Present,

        # If this parameter is set, strings consisting solely of digits with an optional '-' in front
        # which are shorter than the maximum length will be converted to integer variables.
        [Parameter(Mandatory=$false)]
        [ValidateNotNull()]
        [ValidateScript({ $_ -gt 0 -and $_ -le 6})]
        [Int]$convertIntegersMaxLength,

        # Select if strings "true" and "false" are processed into boolean $true and $false
        [Parameter(Mandatory=$false)]
        [Switch]$convertBooleans = [Switch]::Present,

        # Select if strings should be trimmed of starting and trailing whitespace.
        [Parameter(Mandatory=$false)]
        [Switch]$trimStrings
    )

    try {
        # Remove extra first line for Excel if present
        if ($csvString -like "sep=,*") {
            $csvString = [Regex]::new("sep=,[\s]+([\s\S]*)").Match($csvString).Groups[1].Value
        }

        # Output CSV string to temporary file
        # Try to create a temporary file
        try {
            $tempFile = New-TemporaryFile
        }
        catch {
            Write-Error "Exception while creating temporary file for converting CSV string to CSV object.`r`n$($_.Exception.Message)"
            return
        }
        if (!$tempFile) {
            Write-Error "Failed to create temporary file for converting CSV string to CSV object."
            return
        }

        # Try to set the content of the temporary file
        try {
            $csvString | Set-Content -NoNewline -Path $tempFile.FullName -Encoding BigEndianUnicode
        }
        catch {
            Write-Error "Exception while setting content of temporary file for converting CSV string to CSV object.`r`n$($_.Exception.Message)"
            return
        }

        # Try to import CSV file to object
        try {
            $csvObject = Import-Csv -Path $tempFile.FullName -Encoding BigEndianUnicode
        }
        catch {
            Write-Error "Exception while importing temporary file into CSV object.`r`n$($_.Exception.Message)"
            return
        }
        if (!$csvObject) {
            Write-Error "Failed to import temporary file into CSV object."
            return
        }

        # Trim the headers
        if ($trimHeaders) {
            $csvObject = $csvObject | ForEach-Object -Process {
                $updatedObject = [PSCustomObject]@{}
                foreach ($property in $_.PSObject.Properties) {
                    $updatedObject | Add-Member -NotePropertyName $property.Name.Trim() -NotePropertyValue $property.Value
                }
                $updatedObject
            }
        }

        # Convert single objects to array
        try {
            $csvObject = ConvertTo-Array $csvObject
        }
        catch {
            Write-Error "Exception while converting CSV object to an array.`r`n$($_.Exception.Message)"
            return
        }
        if (!$csvObject) {
            Write-Error "Failed to convert CSV object to an array."
            return
        }

        # Process the CSV
        if ($convertIntegersMaxLength -or $convertBooleans -or $trimStrings) {
            # Iterate through each of the rows
            foreach ($csv in $csvObject) {
                # Iterate through each of the columns
                foreach ($propertyName in $csv.PSObject.Properties.Name) {
                    # Check that the entry is not null
                    if ($null -ne $csv.$propertyName) {
                        # Check if the entry is a string
                        if ($csv.$propertyName.GetType() -eq [String]) {
                            # Check if string should be converted to an integer
                            if ($convertIntegersMaxLength -and $csv.$propertyName.length -le $convertIntegersMaxLength -and
                                [Regex]::new("^-?[0-9]{1,$($convertIntegersMaxLength)}$").IsMatch($csv.$propertyName)) {
                                $csv.$propertyName = [Int]$csv.$propertyName
                            }

                            # Check if string should be converted to boolean
                            elseif ($convertBooleans -and $csv.$propertyName.ToLower().Trim() -in @("true", "false")) {
                                $csv.$propertyName = $csv.$propertyName.Trim() -eq "true"
                            }

                            # Check if string should be trimmed
                            elseif ($trimStrings) {
                                $csv.$propertyName = $csv.$propertyName.Trim()
                            }
                        }
                    }
                }
            }
        }

        # Return the converted CSV object
        return $csvObject
    }
    finally {
        # Delete the temporary file created
        if ($tempFile) {
            $tempFile | Remove-Item
        }
    }
}