Functions/Convert-CsvObjectToString.ps1

<#
.SYNOPSIS
    This function converts a CSV object to a CSV string.
.DESCRIPTION
    This function converts a CSV object to a CSV string.
    The CSV object is represented as an array of PSObjects.
#>

function Convert-CsvObjectToString {
    [CmdletBinding(PositionalBinding=$true)]
    [OutputType([String])]
    param (
        # The object containing properties to convert to CSV.
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateNotNull()]
        [PSObject[]]$csvObject,

        # Select the stream where the failure messages will be directed.
        [Parameter(Mandatory=$false)]
        [ValidateSet("Information", "Warning", "Error")]
        [String]$outputStream = "Error"
    )

    try {
        # Output CSV object to temporary file
        # Try to create a temporary file
        try {
            $tempFile = New-TemporaryFile
        }
        catch {
            Invoke-Expression "Write-$($outputStream) 'Exception while creating temporary file for converting CSV object to CSV string.$($CLRF + $_.Exception.Message)'"
            return
        }
        if (!$tempFile) {
            Invoke-Expression "Write-$($outputStream) '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 {
            Invoke-Expression "Write-$($outputStream) 'Exception while exporting CSV object into temporary file.$($CLRF + $_.Exception.Message)'"
            return
        }

        # Try to get content of temporary file to CSV string
        try {
            $csvString = Get-Content $tempFile.FullName -Raw -Encoding BigEndianUnicode
        }
        catch {
            Invoke-Expression "Write-$($outputStream) 'Exception while getting content of temporary file into CSV string.$($CLRF + $_.Exception.Message)'"
            return
        }
        if ([String]::IsNullOrWhiteSpace($csvString)) {
            Invoke-Expression "Write-$($outputStream) 'Failed to get content of temporary file into CSV string.'"
            return
        }

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