Functions/ConvertTo-CsvString.ps1

<#
.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 {
    [CmdletBinding()]
    [OutputType([String])]
    param (
        # The object containing properties to convert to CSV
        [Parameter(Mandatory = $true)]
        [AllowEmptyCollection()]
        [ValidateNotNull()]
        [PSObject[]]$csvObject
    )

    try {
        # The CSV object is empty
        if ($csvObject.length -eq 0 -or $csvObject.count -eq 0) {
            return
        }

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

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

        # Try to get content of temporary file to CSV string
        try {
            $csvString = Get-Content $tempFile.FullName -Raw -Encoding BigEndianUnicode
        }
        catch {
            Write-Error "Exception while getting content of temporary file into CSV string.`r`n$($_.Exception.Message)"
            return
        }
        if (!$csvString) {
            Write-Error "Failed to get content of temporary file into CSV string."
            return
        }

        # Add extra line so that Excel is able to process it properly
        $csvString = "sep=,`r`n" + $csvString
        return $csvString
    }
    finally {
        # Delete the temporary file created
        if ($tempFile) {
            $tempFile | Remove-Item
        }
    }
}