Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select-Object of multiple properties

Tags:

powershell

I am trying to find an elegant way to put the metadata of a table of type System.Data.DataTable into a multi-dimensional array for easy reference in my program. My approach to the issue so far seems tedious.

Assuming $DataTable being the DataTable in question

What I tried to do so far was:

$Types = $DataTable.Columns | Select-Object -Property DataType
$Columns= $DataTable.Columns | Select-Object -Property ColumnName
$Index = $DataTable.Columns | Select-Object -Property ordinal
$AllowNull  = $DataTable.Columns | Select-Object -Property AllowDbNull

Then painfully going through each array, pick up individual items and put them in my multi-dimensional array $TableMetaData.

I read in the documentation of Select-Object and it seems to me that only 1 property can be selected at 1 time? I think I should be able to do all the above more elegantly and store the information in $TableMetaData.

Is there a way to easily pick up multiple properties and put them in a multi-dimensional array in 1 swoop?

like image 839
user1205746 Avatar asked May 23 '17 18:05

user1205746


People also ask

How do you select an object property?

To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters. To select object properties, use the Property parameter. When you select properties, Select-Object returns new objects that have only the specified properties.

Which two commands used to filter only selected properties?

Using the Where-Object and Select-Object commands allows you to easily control which items you are working on in PowerShell. You can use these commands to either filter the data you are viewing or to limit actions (such as stopping services or removing files) to those that match the filters you define.


1 Answers

I read the documentation of Select-Object and it seems to me that only 1 property can be selected at 1 time?

This is not true, Select-Object can take any number of arguments to the -Property parameter

$ColumnInfo = $DataTable.Columns | Select-Object -Property DataType,ColumnName,ordinal,AllowDbNull

Now $ColumnInfo will contain one object for each column, having all 4 properties.

Rather than using a multi-dimensional array, you should consider using a hashtable (@{}, an unordered dictionary):

$ColumnInfo = $DataTable.Columns | ForEach-Object -Begin { $ht = @{} } -Process {
    $ht[$_.ColumnName] = $_
} -End { return $ht }

Here, we create an empty hashtable $ht (the -Begin block runs just once), then store each column object in $ht using the ColumnName as the key, and finally return $ht, storing it in $ColumnInfo.

Now you can reference metadata about each column by Name:

$ColumnInfo.Column2
# or 
$ColumnInfo["Column2"]
like image 142
Mathias R. Jessen Avatar answered Sep 28 '22 08:09

Mathias R. Jessen