I love using tables in my powershell scripts. Since it is always a lot of repeating code to create them if I need different tables, I decided to create a function that returns a fully functional table to me.
My try thus far looks like this:
Function MakeTable ($btab, $TableName, $ColumnArray)
{
$btab = New-Object System.Data.DataTable("$TableName")
foreach($Col in $ColumnArray)
{
$MCol = New-Object System.Data.DataColumn $Col;
$btab.Columns.Add($MCol)
}
}
$acol = @("bob","wob","trop")
$atab = $null
MakeTable $atab "Test" $acol
Alternatively I tried:
Function MakeTable ($TableName, $ColumnArray)
{
$btab = New-Object System.Data.DataTable("$TableName")
foreach($Col in $ColumnArray)
{
$MCol = New-Object System.Data.DataColumn $Col;
$btab.Columns.Add($MCol)
}
return $btab
}
$acol = @("bob","wob","trop")
$atab = MakeTable "Test" $acol
I tested both versions with the same code:
$aRow = $atab.NewRow()
$aRow["bob"] = "t1"
$aRow["wob"] = "t2"
$aRow["trop"] = "t3"
$atab.Rows.Add($aRow)
$atab
Both sadly didn't do what I expected.
You cannot call a method on a null-valued expression.
At line:13 char:1
+ $aRow = $atab.NewRow()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Can you help me?
EDIT:
$Global:atab = New-Object System.Data.DataTable("")
$Global:btab = New-Object System.Data.DataTable("")
Function MakeTable ($x, $TableName, $ColumnArray)
{
if($x -eq 1)
{
$xtab = $Global:atab
}
elseif($x -eq 2)
{
$xtab = $Global:btab
}
$xTab.TableName = $TableName
foreach($Col in $ColumnArray)
{
$MCol = New-Object System.Data.DataColumn $Col;
$xTab.Columns.Add($MCol)
}
}
$acol = @("bob","wob","trop")
MakeTable 1 "Test" $acol
$aRow = $Global:atab.NewRow()
$aRow["bob"] = "t1"
$aRow["wob"] = "t1"
$aRow["trop"] = "t1"
$Global:atab.Rows.Add($aRow)
$Global:atab
This is doing what I want, but not really. I think there is a much better way.
$atabgets assigned. In the second, you return from within theforeachso only the first column will be added.