# encoding: ascii
# api: powershell
# title: Get-CrystalReportTable
# description: Find the tables used in a Crystal Report.
# version: 0.1
# type: function
# license: CC0
# function: Get-CrystalReportTable
# x-poshcode-id: 1471
# x-archived: 2010-01-17T22:10:00
#
#
function Get-CrystalReportTable()
{
    #Requires -Version 2
    <#
    .Synopsis
        Examines a Crystal Report and returns the tables used
    .Description
        Examines a Crystal Report and returns the tables used by the main report and subreports
    .Example
        $reports = Dir *.rpt | Get-CrystalReportTable
    .Notes
        Written by Steven Murawski on 11/12/09
        http://blog.usepowershell.com
        Version 0.1
    #>
    [cmdletbinding()]
    param (
        [parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
        [Alias('FullName')]
        [string]$Path
    )
    begin
    {
        [reflection.assembly]::LoadWithPartialName('CrystalDecisions.Shared') | Out-Null
        [reflection.assembly]::LoadWithPartialName('CrystalDecisions.CrystalReports.Engine') | Out-Null
    }
    process
    {
        try
        {
            $output = New-Object PSObject | Select-Object Name, Tables, SubReports
            $output.name = Split-Path $path -Leaf
            
            $report = New-Object CrystalDecisions.CrystalReports.Engine.ReportDocument 
            $report.load($path)
            $output.Tables = $report.Database.Tables | Select-Object -expand Name
            
            
            $subreports = @($report.ReportDefinition.ReportObjects | Where-Object {$_ -is [CrystalDecisions.CrystalReports.Engine.SubreportObject]})
            if ($subreports.count -gt 0 )
            {
                $output.subreports = @()
                foreach ($subreport in $subreports)
                {
                    $subreportdata = New-Object PSObject | Select-Object Name, Tables
                    $subreportdata.name = $subreport.SubreportName
                    
                    $subreportobject = $report.OpenSubreport($subreport.SubreportName)
                    $subreportdata.Tables = $subreportobject.Database.Tables | Select-Object -expand Name
                    $output.subreports += $subreportdata
                }
            }          
            Write-Output $output
        }
        finally
        {
            $report.dispose()   
        }
    }
}
