Try Add-Type to execute C# in PowerShell: executing-c-code-in-powershell
Powershell Load DataTable to Multi Dimensional Array
Okay,
THis should be simple, but thus far i have not been able to do this without annoying over-typed for loops and a lot of other hooplah that shouldn't be needed.
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=$($serverName);Integrated Security=true";
$conn.Open();
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT Name, Value FROM mydb.dbo.Table";
$table = New-Object System.Data.DataTable
$table.Load($cmd.ExecuteReader())
$conn.Close();
$column = $table.Columns[0].ColumnName
$data = @($table | select -ExpandProperty $column)
That above gives me an array of the first column, but i want it to get me an array of the row data. so each row has an "array of values" and i want an array of those arrays.
The C# equivalent would be:
object[][] data = table.OfType<DataRow>().Select(r => r.ItemArray)
or to be more type specific:
string[][] data = table.OfType<DataRow>().Select(r => r.ItemArray.Select(c => c.ToString()).ToArray())
Thus far, i cannot seem to do this is a simple statement or pair of statements in PowerShell, i seem to require doing some form of loop, or create custom objects, etc.
i just want the data formatted into arrays.
Thanks
Jaeden "Sifo-Dyas" al'Raec Ruiner
Windows for business | Windows Server | User experience | PowerShell
3 answers
Sort by: Most helpful
-
-
Anonymous
2020-11-16T09:05:44.977+00:00 Hi,
In powershell you can create a two dimensional array in this way
[string[,]]$data = [string[,]]::new(5,5)
Best Regards,
Ian============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread. -
Anonymous
2020-11-17T09:52:22.523+00:00 Hi,
Sorry for the misunderstanding. You can create an array of arrays like this
[array[]]$data = [array[]]::new(5)
Best Regards,
Ian============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.