I whipped this up, but it doesn't seem like the most efficient way:
foreach ($i in 0..($reader.FieldCount - 1)) {
$row += $null
}
Is there a better way to gin up an empty array of a specific size (a
contradiction, I know, but you know what I mean)?
---
Shay Levy
Windows PowerShell MVP
http://blogs.microsoft.co.il/blogs/ScriptFanatic
t> Okay, so I'm trying to use the SqlDataReader.GetValues() method, and
t> it wants me to pass it an array. The problem is that it wants the
t> array to be at least as large as the data that I want to put it in,
t> otherwise the data gets truncated.
t>
t> I whipped this up, but it doesn't seem like the most efficient way:
t>
t> foreach ($i in 0..($reader.FieldCount - 1)) {
t> $row += $null
t> }
t> Is there a better way to gin up an empty array of a specific size (a
t> contradiction, I know, but you know what I mean)?
t>
You could also use a static method CreateInstance of the Array class
(hat tip to /\/\o\/\/):
PS> $arr = [array]::CreateInstance([object],$reader.FieldCount)
In some cases, this approach is also good when you want to control the
array's element type:
PS>$a = [array]::CreateInstance([datetime],10)
PS>$a[0] = "test"
Array assignment to [0] failed: Cannot convert value "test" to type
"System.DateTime". Error: "The string was not recognized as a valid
DateTime. There is a unknown word starting at index 0.".
At line:1 char:4
+ $a[0 <<<< ] = "test"
-aleksandar
http://powershellers.blogspot.com
Thanks guys. I knew there was a way to do that, but I couldn't find
it.
This came up on #powershell some time ago and I blogged a really short solution.
Then Bruce Payette followed up with more info which was awesome, so click the
link to see that.
http://halr9000.com/article/430
method 1:
$array = ,0 * 20
method 2:
$array = @(0) * 20
--
Author, Tech Prosaic blog (http://halr9000.com)
Webmaster, Psi (http://psi-im.org)
Community Director, PowerShellCommunity.org
Co-host, PowerScripting Podcast (http://powerscripting.net)