0

I need to copy a collection of 10 items into an array so I can index into it. So I need to use the CopyTo method and specify a destination array large enough to accommodate the collection.

So before calling CopyTo I need to dim an empty array of a specific size. I can't seem to find the correct PowerShell syntax for doing this.

This didn't work for me:

$snapshot = New-Object System.Array 10;

New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Array.

Edit

Have worked around it with:

$snapshot = New-Object System.Collections.ArrayList;
$snapshot.AddRange($slider);  
Luke Puplett
  • 42,091
  • 47
  • 181
  • 266
  • possible duplicate of [PowerShell array initialization](http://stackoverflow.com/questions/226596/powershell-array-initialization) – Filburt Jul 24 '14 at 12:47

2 Answers2

0

I think this should do the trick:

$snapshot = @()

Edit:
Ok, sorry about that. Tested this one:

> $snapshot  = New-Object object[] 10
> $snapshot.Length 
10
marosoaie
  • 2,352
  • 23
  • 32
0

I think just creating a new array will accomplish that in Powershell.

# A "collection of ten items"
$collection = @(1,2,3,4,5,6,7,8,9,0)

#This command creates a new array, sizes it, and copies data into the new array
$newCollection = $collection

Powershell creates a new array in this case. No need to specify the size of the array; Powershell sizes it automatically. And if you add an element to the array, Powershell will take care of the tedious initializeNew-copy-deleteOld routine you have to do in lower-level languages.

Note that $newCollection isn't a reference to the same array that $collection references. It's a reference to a whole new array. Modifying $collection won't affect $newCollection, and vice-versa.

Bagheera
  • 1,358
  • 4
  • 22
  • 35
  • Unfortunately this does not address my needs. I need an empty array of a specific length. I'm working with custom collection types from a .NET library rather than purely manipulating PS arrays. – Luke Puplett Jul 24 '14 at 12:36