Csv.psm1

<#
.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 {
    param (
        # The string containing the CSV representation.
        [Parameter(Mandatory=$true)]
        [String]$csvString
    )

    # Remove extra first line for Excel if present
    if ($csvString -like "sep=,*") {
        $csvString = $csvString.Remove(0, $csvString.IndexOf('"'))
    }

    # Output CSV string to temporary file
    # Try to create a temporary file
    try {
        $tempFile = New-TemporaryFile
    }
    catch {
        Write-Error "Failed to create temporary file for converting CSV string to CSV object. $($_.Exception.Message)"
        return [PSCustomObject]@{}
    }

    # Try to set the content of the temporary file
    try {
        $csvString | Set-Content -NoNewline -Path $tempFile.FullName
    }
    catch {
        Write-Error "Failed to set content of temporary file for converting CSV string to CSV object. $($_.Exception.Message)"
        return [PSCustomObject]@{}
    }

    # Try to import CSV file to object
    try {
        $csvObject = Import-Csv -Path $tempFile.FullName
    }
    catch {
        Write-Error "Failed to import temporary file into CSV object. $($_.Exception.Message)"
        return [PSCustomObject]@{}
    }
    return $csvObject
}

<#
.SYNOPSIS
    This function converts a CSV object to a CSV string.
.DESCRIPTION
    This function takes in a custom object and returns the CSV representation
    of that object as a single string.
.PARAMETER csvObject
    The object containing properties to convert to CSV.
#>

function ConvertTo-CsvString {
    param (
        # The object containing properties to convert to CSV
        [Parameter(Mandatory = $true)]
        [PSObject]$csvObject
    )

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

    # Try to export CSV object to temporary file
    try {
        $csvObject | Export-Csv -Path $tempFile.FullName -NoTypeInformation
    }
    catch {
        Write-Error "Failed to export CSV object into temporary file. $($_.Exception.Message)"
        return ""
    }

    # Try to get content of temporary file to CSV string
    try {
        $csvString = Get-Content $tempFile.FullName -Raw
    }
    catch {
        Write-Error "Failed to get content of temporary file to CSV string. $($_.Exception.Message)"
        return ""
    }

    # Add extra line so that Excel opens properly
    $csvString = "sep=,`r`n" + $csvString
    return $csvString
}