$ErrorActionPreference = "Stop"

$WorkbookPath = Get-ChildItem -Path (Get-Location) -Filter "*.xlsx" |
    Where-Object { $_.Name -like "SaaS_E2E*" -and $_.Name -notlike "*副本*" } |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1 -ExpandProperty FullName

$excel = $null
$workbook = $null

try {
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $false
    $workbook = $excel.Workbooks.Open($WorkbookPath)
    foreach ($worksheet in $workbook.Worksheets) {
        $used = $worksheet.UsedRange
        for ($row = 2; $row -le $used.Rows.Count; $row++) {
            $caseId = ([string]$worksheet.Cells.Item($row, 1).Text).Trim()
            if ($caseId -ne "F-MAIN-002") {
                continue
            }
            Write-Host "sheet=$($worksheet.Name) row=$row"
            for ($column = 1; $column -le $used.Columns.Count; $column++) {
                $header = [string]$worksheet.Cells.Item(1, $column).Text
                $value = [string]$worksheet.Cells.Item($row, $column).Text
                Write-Host "[$column] $header = $value"
            }
        }
    }
}
finally {
    if ($workbook -ne $null) {
        $workbook.Close($false)
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    }
    if ($excel -ne $null) {
        $excel.Quit()
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
    }
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
