Home > Software engineering >  PowerShell is re-arranging my columns and i cant figure out why
PowerShell is re-arranging my columns and i cant figure out why

Time:12-23

the code I am using is below

    New-Object PSObject -Property @{
        Product = $_.Name 
        Stockcode = $_.Group[0].Stockcode
        QuantityCounted = ($_.Group | Measure-Object -Property QuantityCounted -Sum).Sum    
    }
}| Export-Csv "E:\CSV\test.csv" -NoTypeInformation  

The Headers should be in this order Product | Stockcode | QuantityCounted

enter image description here

if someone could point me in the right direction that would awesome, thank you

CodePudding user response:

Hashtables are not ordered by default unless you force them to:

New-Object PSObject -Property (
[ordered]@{
    Product = 1
    Stockcode = 2
    QuantityCounted = 3
})

Also, unless you're running an old version of PowerShell:

The [pscustomobject] type accelerator was added in PowerShell 4.0.

[pscustomobject]@{
    Product = 1
    Stockcode = 2
    QuantityCounted = 3
}

PSCustomObject is ordered by default and more efficient.

  • Related