functions/Export-DbaDiagnosticQuery.ps1

function Export-DbaDiagnosticQuery {
    <#
        .SYNOPSIS
            Export-DbaDiagnosticQuery can convert ouput generated by Invoke-DbaDiagnosticQuery to CSV or Excel
 
        .DESCRIPTION
            The default output format of Invoke-DbaDiagnosticQuery is a custom object. It can also output to CSV and Excel.
            However, CSV output can generate a lot of files and Excel output depends on the ImportExcel module by Doug Fike (https://github.com/dfinke/ImportExcel)
            Export-DbaDiagnosticQuery can be used to convert from the default export type to the other available export types.
 
        .PARAMETER InputObject
            Specifies the objects to convert
             
        .PARAMETER ConvertTo
            Specifies the output type. Valid choices are Excel and CSV. CSV is the default.
             
        .PARAMETER Path
            Specifies the path to the output files.
 
        .PARAMETER Suffix
            Suffix for the filename. It's datetime by default.
 
        .PARAMETER Silent
            Use this switch to disable any kind of Output messages
 
        .NOTES
            Tags: Query
            Author: André Kamman (@AndreKamman), http://clouddba.io
 
            Website: https://dbatools.io
            Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
            License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
        .LINK
            https://dbatools.io/Export-DbaDiagnosticQuery
 
        .EXAMPLE
            Invoke-DbaDiagnosticQuery -SqlInstance sql2016 | Export-DbaDiagnosticQuery -Path c:\temp
 
            Converts output from Invoke-DbaDiagnosticQuery to multiple CSV files
             
        .EXAMPLE
            $output = Invoke-DbaDiagnosticQuery -SqlInstance sql2016
            Export-DbaDiagnosticQuery -InputObject $output -ConvertTo Excel
 
            Converts output from Invoke-DbaDiagnosticQuery to Excel worksheet(s) in the Documents folder
    #>

    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [object[]]$InputObject,
        [ValidateSet("Excel", "Csv")]
        [string]$ConvertTo = "Csv",
        [System.IO.FileInfo]$Path = [Environment]::GetFolderPath("mydocuments"),
        [string]$Suffix = "$(Get-Date -format 'yyyyMMddHHmmssms')",
        [switch]$Silent
    )
    
    begin {
        if ($ConvertTo -eq "Excel") {
            try {
                Import-Module ImportExcel -ErrorAction Stop
            }
            catch {
                $message = "Failed to load module, exporting to Excel feature is not available
                            Install the module from: https://github.com/dfinke/ImportExcel
                            Valid alternative conversion format is csv"

                Stop-Function -Message $message
                return
            }
        }

        if(!$(Test-Path $Path)) {
            try 
            {                
                New-Item $Path -ItemType Directory -ErrorAction Stop | Out-Null
                Write-Message -Level Output -Message "Created directory $Path"
            } catch {
                Stop-Function -Message "Failed to create directory $Path" -Continue
            }
        }
        
        Function Remove-InvalidFileNameChars {
            [CmdletBinding()]
            param (
                [Parameter(Mandatory = $true,
                           Position = 0,
                           ValueFromPipeline = $true,
                           ValueFromPipelineByPropertyName = $true)]
                [String]$Name
            )
            $Name = $Name.Replace(" ","-")
            $invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
            $re = "[{0}]" -f [RegEx]::Escape($invalidChars)
            return ($Name -replace $re)
        }
    }
    
    process {
        if (Test-FunctionInterrupt) { return }
        
        foreach ($row in $InputObject) {
            $results = $row.Result
            $name = $row.Name
            $SqlInstance = $row.SqlInstance.Replace("\", "$")
            $dbname = $row.DatabaseName
            $number = $row.Number
            
            if ($null -eq $results){
                Stop-Function -Message "Resultset was empty for $name" -Target $row -Continue
            }
            
            foreach ($result in $results) {
                
                if ($null -eq $result) {
                    Stop-Function -Message "Result was empty for $name" -Target $result -Continue
                }
                
                $queryname = Remove-InvalidFileNameChars -Name $Name
                $excelfilename = "$Path\$SqlInstance-DQ-$Suffix.xlsx"
                $exceldbfilename = "$Path\$SqlInstance-DQ-$dbname-$Suffix.xlsx"
                $csvdbname = "$Path\$SqlInstance-$dbname-DQ-$number-$queryname-$Suffix.csv"
                $csvfilename = "$Path\$SqlInstance-DQ-$number-$queryname-$Suffix.csv"
                
                switch ($ConvertTo) {
                    "Excel"
                    {
                        if ($result.dbSpecific) {
                            Write-Message -Level Output -Message "Exporting $exceldbfilename"
                            $result.result | Export-Excel -Path $exceldbfilename -WorkSheetname $result.Name -AutoSize -AutoFilter -BoldTopRow -FreezeTopRow
                        }
                        else {
                            Write-Message -Level Output -Message "Exporting $excelfilename"
                            $result.result | Export-Excel -Path $excelfilename -WorkSheetname $result.Name -AutoSize -AutoFilter -BoldTopRow -FreezeTopRow
                        }
                    }
                    "csv"
                    {
                        if ($result.dbSpecific) {
                            Write-Message -Level Output -Message "Exporting $csvdbfilename"
                            $result | Export-Csv -Path $csvdbfilename -NoTypeInformation -Append
                        }
                        else {
                            Write-Message -Level Output -Message "Exporting $csvfilename"
                            $result | Export-Csv -Path $csvfilename -NoTypeInformation -Append
                        }
                    }
                }
            }
        }
    }
}