PowerShell Create a series in System.Object (PSCustomObject)

Viewed 43

Is there an easier way to accomplish this without typing the series out? I tried some ideas with arrays and dereferencing, but nothing ended up working.

$rowP = "" | Select-Object Course,"5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35"
1 Answers

I prefer the following approach.

  1. Create an ordered dictionary:
$properties = [ordered]@{
  Course = $null
}
  1. Use the .. range operator to generate the range of integers 5 through 35, add empty entries to the dictionary:
5..35 |ForEach-Object {
  $properties["${_}"] = $null
}
  1. Convert the dictionary to a PSCustomObject:
$object = [pscustomobject]$properties

Alternatively, you could also use the range operator to generate the integer range and pass those as property names to Select-Object:

"" |Select-Object -Property @('Course'; 5..35 -as [string[]])
Related