notes, references

January 25, 2011

powershell array, add, remove elements

Filed under: Uncategorized — Tags: — karthik @ 12:13 pm

Arrays are convenient to use but like in any language adding removing elements dynamically is not very efficient. It is more efficient to use System.Collections.ArrayList or generic List class (instantiating generics is another topic) than Arrays

PS >
PS > [array]$names = @()
PS > $names += "Q"
PS > $names += "picard"
PS > $names += "spock"
PS > $names += 10

PS > $names.Count
4

PS > $names[2]
spock

PS > $names[6]

PS > $names
Q
picard
spock
10
PS >
PS > $names.count = 2
"Length" is a ReadOnly property.
At line:1 char:8
+ $names. <<<< count = 2
 + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
 + FullyQualifiedErrorId : PropertyAssignmentExceptionPS >

PS > $names.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS > $names[4]
10
PS > $names[4].GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

PS > $names[2]
spock
PS > $names[2].GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

When declaring an array of one, it might not be an Array

Consider an array of arrays, an array of two elements, each element is in turn an array

PS> $a = @( @("row1-a", "row1-b", "row1-c"), @("row2-a", "row2-b") )
PS> $a.count
2
PS>$a[0].count
3
PS>$a[1].count
2

Now an array of one – not what we would normally expect

PS> $a = @( @("row1-a", "row1-b", "row1-c") )
PS> $a.Count
3

$a becomes just array of three strings instead of an array of 1 element, to get this you have to start the array declaration with a comma

PS> $a = @(, @("row1-a", "row1-b", "row1-c") )
PS> $a.Count
1

Starting an array with more than one element with a comma is fine, it does not add an extra empty element at the beginning :) 

References:

http://www.vistax64.com/powershell/13950-how-add-entries-array.html

http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/

http://stackoverflow.com/questions/1390782/jagged-powershell-array-is-losing-a-dimension-when-only-one-element-exists

http://www.justaprogrammer.net/2011/03/30/an-array-of-one-item-in-powershell/

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.