• You could use the Open Source DLL EPPlus to write the output from a SQL query directly to an Excel spreadsheet, e.g.,

    $cmdText = "select object_name(i.object_id) as [Table Name], i.name as [Index Name], case when i.type = 1 then 'Clustered' else 'Nonclustered' end as [Index Type], i.fill_factor as [Fill Factor], s.avg_fragmentation_in_percent as Fragmentation, s.page_count as [Page Count]

    from sys.dm_db_index_physical_stats(db_id(), null, null, null, null) s

    inner join sys.indexes i with (nolock) on i.object_id = s.object_id and i.index_id = s.index_id

    where i.name is not null

    and s.avg_fragmentation_in_percent > 5

    and s.page_count > 1000

    order by s.avg_fragmentation_in_percent desc"

    $dt = New-Object System.Data.DataTable

    $da = New-Object System.Data.SqlClient.SqlDataAdapter $cmdText, "Server=???;Database=???;Trusted_Connection=Yes"

    $da.SelectCommand.CommandTimeout = 300

    [void]$da.Fill($dt)

    $file = New-Object System.IO.FileInfo ("Book1.xlsx")

    if (Test-Path $file.FullName) {Remove-Item $file.FullName}

    Import-Module ($env:USERPROFILE + "\Documents\WindowsPowerShell\EPPlus.dll")

    $package = New-Object OfficeOpenXml.ExcelPackage $file

    $sheet = $package.Workbook.Worksheets.Add("Sheet1")

    [void]$sheet.Cells["A1"].LoadFromDataTable($dt, $true)

    $sheet.Row(1).Style.Font.Bold = $true

    $sheet.View.FreezePanes(2, 1)

    $sheet.Cells.AutoFitColumns()

    $sheet.Column(4).Style.NumberFormat.Format = "#,##0"

    $sheet.Column(5).Style.NumberFormat.Format = "##0.00"

    $sheet.Column(6).Style.NumberFormat.Format = "#,##0"

    [void]$package.Save()

    $package.Dispose()

    [void][System.Diagnostics.Process]::Start($file.FullName)