Technical Insights • • 1 min read
Get a Header into an Array
Three ways to add property names to a plain PowerShell array so you can access elements via named properties instead of index positions.
Today I was asked how to add a “header” to an array – so you can access its contents via a property like $obj.AccountName instead of by index.
The inspiration came from Import-Csv -Header. Here are three solutions:
1. Explicit – with a Class
class User {
[String]$Accountname
User ([String[]]$Username) {
$this.Accountname = $Username
}
}
@('myUser', 'YourUser') | ForEach-Object { [User]::new($_) }
2. Implicit – with Select-Object (shorter)
@('myUser', 'YourUser') | Select-Object @{ l = 'Accountname'; e = { $_ } }
3. Implicit – with PSCustomObject
@('myUser', 'YourUser') | ForEach-Object {
[PSCustomObject]@{ Accountname = $_ }
}
Results
In all three cases the output is an Object[]. The difference: the class version contains strongly-typed User objects, while the other two produce generic PSCustomObject instances.