$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 -notlike "S-*") {
                continue
            }
            $title = [string]$worksheet.Cells.Item($row, 5).Text
            $basis = [string]$worksheet.Cells.Item($row, 3).Text
            Write-Host "$($worksheet.Name)!$row | $caseId | $title | $basis"
        }
    }
}
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()
}
