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
Author: André Kamman (@AndreKamman), http://clouddba.io
 
dbatools PowerShell module (https://dbatools.io, clemaire@gmail.com)
Copyright (C) 2016 Chrissy LeMaire
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
 
.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
            }
        }
        
        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
            $sqlserver = $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\$sqlserver-DQ-$Suffix.xlsx"
                $exceldbfilename = "$Path\$sqlserver-DQ-$dbname-$Suffix.xlsx"
                $csvdbname = "$Path\$sqlserver-$dbname-DQ-$number-$queryname-$Suffix.csv"
                $csvfilename = "$Path\$sqlserver-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
                        }
                    }
                }
            }
        }
    }
}