OnesimusUnbound
OnesimusUnbound

Reputation: 2946

How to stop Powershell from flattening parameter of jagged array?

I created a hashtable representing the structure of the file I'm extracting data from

# schema of the data stored in the file
$RecordSchema = @{
    Header = @(
        @("EmployerName",       2, 30)
        @("ApplicableMonth",    32, 6)
        @("EmployerIDNumber",   38, 10)
    )
}

# function to extract data from the file based on the $schema
function Map-Field ($row, $schema) {
    $mappedRow = @{}
    foreach ($field in $schema) {
        $fieldName = $field[0]
        $fieldPosition = $field[1]
        $fieldSize = $field[2]

        $value = $row.Substring($fieldPosition, $fieldSize)
        $mappedRow[$fieldName] = $value
    }

    [PSCustomObject]$mappedRow
}

function Set-RecordHeader($record, $recordRaw) {
    $record["Header"] = Map-Field $recordRaw[0] $RecordSchema["Header"]
    $record
}

When I run the script, $schema gets the flattened version of the schema $RecordSchema.Header I've passed.

I've added comma before the parameter $RecordSchema["Header"] yet I got an array of single-item array and that item contains the flattened version of the schema I'm passing.

$record["Header"] = Map-Field $recordRaw[0] (,$RecordSchema["Header"]) 

Upvotes: 1

Views: 207

Answers (1)

OnesimusUnbound
OnesimusUnbound

Reputation: 2946

I've just discovered that for some reason, I need to add a comma at the end of each array

$RecordSchema = @{
    Header = @(
        @("EmployerName",       2, 30), # this
        @("ApplicableMonth",    32, 6), # and other comma matter
        @("EmployerIDNumber",   38, 10)
    )
}

I verified it by running the following

$a = @(
    @(1, 2, 3)
    @(4, 5, 6)
)

$b = @(
    @(1, 2, 3),
    @(4, 5, 6)
)

$a.Length # returns 6
$b.Length # returns 2

I've thought PowerShell will think that passing a new line means another entry :-(

Upvotes: 2

Related Questions