Private/Assert-FSMCsvColumn.ps1
|
function Assert-FSMCsvColumn { <# .SYNOPSIS Confirms an imported CSV (or object collection) contains the required columns. .DESCRIPTION Import-Csv produces objects whose properties are the CSV's column headers. Under Set-StrictMode, reading a property that doesn't exist throws a cryptic error. This helper checks up front and throws a clear, actionable message instead, naming the file and the missing columns. .PARAMETER InputObject The first row (or whole collection) imported from the CSV. .PARAMETER RequiredColumn The column names that must be present. .PARAMETER Path The source file path, used only to make the error message specific. #> [CmdletBinding()] param( [Parameter(Mandatory)] [AllowNull()] $InputObject, [Parameter(Mandatory)] [string[]]$RequiredColumn, [string]$Path = '<input>' ) $firstRow = @($InputObject) | Select-Object -First 1 if ($null -eq $firstRow) { throw "The file '$Path' contains no rows. Expected columns: $($RequiredColumn -join ', ')." } $present = $firstRow.PSObject.Properties.Name $missing = $RequiredColumn | Where-Object { $_ -notin $present } if ($missing) { throw ("The file '{0}' is missing required column(s): {1}. Columns found: {2}." -f ` $Path, ($missing -join ', '), ($present -join ', ')) } } |