In short I am pulling data from a SQl stored procedure into an ArrayList of a custom class and I am somehow ending up with extra null items. One for each item pulled back, so if there are 15 items returned from the SQL stored procedure, I end up with an array of 30. Any help figuring out why I am getting extra items, or how to remove them would be greatly appreciated.
Function Execute-Procedure
{
Param
(
[Parameter(Mandatory=$true)][string]$parameter,
[Parameter(Mandatory=$true)]
[System.Data.SqlClient.SqlConnection]$sqlconnection
)
Process
{
$items = [System.Collections.ArrayList]@()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $sqlconnection
$cmd.CommandTimeout = 0
$cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
$cmd.CommandText = "My_Stored_Procedure"
$cmd.Parameters.AddWithValue("@PARAMETER",$parameter) | Out-Null
$reader = $cmd.ExecuteReader()
while($reader.Read())
{
$currentItem = [CustomClass]::new()
$currentItem.property1 = $reader.GetValue(0)
$currentItem.property2 = $reader.GetValue(3)
$items.Add($currentItem)
}
$cmd.Dispose() | Out-Null
$reader.Dispose()
return $items
}
}
...
$items = Execute-Procedure $parameter $sqlconnection
$itemCount = $items.Count
"Item count: $itemCount"
foreach($item in $items)
{
$p1 = $item.property1
$p2 = $item.property2
"Property1: $p1 - Property2: $p2"
}
Some sample output:
Item count: 30
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: - property2:
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
property1: 1111 - property2: XXXX
[CustomClass]over and over again. You'll want to create a new instance every time inside thewhileloop$items.Countis 30 even though you only expect 15 items based on the query - and 15 of the items in the array list are$null? Every other? The last 15? The first 15?