Powershell

Hons on the #Powershell IRC channel (@irc.freenode.net) asked this:

“how do I create an array of a specific size? Like in VBScript: ”dim array  20)”, so that I can immediately index into the array”

He went on to explain that he knows a for loop (see below) would work, but he was looking for the quick way.

$array = @(0), for (x=0 to 19) { $array += 0 }

Here is what I came up with:

$array = ,0 * 20

Pro:  It’s quick

Con:  Sure looks funny…

A bit more tweaking came up with this:

$arr = @(0) * 20

I think we’ll call this the “final answer”.  :)

: http://halr9000.com/article/430

2007-09-12 13:20:52

@(123) * 100 works and it has the upside of initializing the collection to a specific value, however if you just want to allocate space, you can do this efficiently with the New-Object cmdlet:

PS (52) > $a = new-object object[] 10
PS (53) > $a.count
10
PS (54) > $a = new-object int[] 30
PS (55) > $a.count
30

-bruce [MSFT]

2007-09-13 06:03:14

Ahh, very good. I just reviewed the help file for new-object and I have to say this usage is not extremely obvious. Guess that’s why we have books like “Powershell in Action”. ;)

2007-09-14 06:57:32

An other option using a static method of the Array class :

PoSH> [array]::CreateInstance([object],5)
PoSH> $a = [array]::CreateInstance([int],5)
PoSH> $a
0
0
0
0
0
PoSH> $a[2] = ‘foo’
Array assignment to [2] failed: Cannot convert value “foo” to type “System.Int
rror: “Input string was not in a correct format.”.

Greetings /\/\o\/\/

2009-01-18 11:52:36

[...] 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 [...]

  • Microblog

  • Recent Posts

  • Recent Comments

  • meta

  • PowerShell Blogroll