Back to Basics: Arrays
In PowerShell, arrays are a wonderfull and very powerfull tools which will help you in your daily labor. Today, i wanna speak about that, returning to the basics and help you mastering it.
Mosts of your scripts deal with multiple servers, files, and more. PowerShell arrays can’t be used like any other data types, you can create, add data, remote it, sort it.
Create an Array
To create a basic array, just declare a variable wih items set separated by commas.
$Array = "one","two","three"
PS D:\> $Array one two three
Kinda easy isn’t it !
Another way to create an array…
$Array = New-Object System.Collections.ArrayList $Array.add(1) $Array.add(2) $Array.add(3) $Array.add("Hourray!")
PS D:\> $Array 1 2 3 Hourray!
Playing with arrays
You see, that you can store multi data type in the same array. let’s see methodes available with this array…
$Array | Get-Member
PS D:\> $Array | Get-Member TypeName : System.Int32 Name MemberType Definition ---- ---------- ---------- CompareTo Method int CompareTo(System.Object value), int CompareTo(int value), in... Equals Method bool Equals(System.Object obj), bool Equals(int obj), bool IEqua... GetHashCode Method int GetHashCode() GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetT... ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) ToChar Method char IConvertible.ToChar(System.IFormatProvider provider) ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider) ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider) ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider) ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider provider) ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider) ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider) ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider) ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider) ToString Method string ToString(), string ToString(string format), string ToStri... ToType Method System.Object IConvertible.ToType(type conversionType, System.IF... ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider provider) ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider provider) ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider provider) TypeName : System.String Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone(), System.Object ICloneable.... CompareTo Method int CompareTo(System.Object value), int CompareT... Contains Method bool Contains(string value) CopyTo Method void CopyTo(int sourceIndex, char[] destination,... EndsWith Method bool EndsWith(string value), bool EndsWith(strin... Equals Method bool Equals(System.Object obj), bool Equals(stri... GetEnumerator Method System.CharEnumerator GetEnumerator(), System.Co... GetHashCode Method int GetHashCode() GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode I... IndexOf Method int IndexOf(char value), int IndexOf(char value,... IndexOfAny Method int IndexOfAny(char[] anyOf), int IndexOfAny(cha... Insert Method string Insert(int startIndex, string value) IsNormalized Method bool IsNormalized(), bool IsNormalized(System.Te... LastIndexOf Method int LastIndexOf(char value), int LastIndexOf(cha... LastIndexOfAny Method int LastIndexOfAny(char[] anyOf), int LastIndexO... Normalize Method string Normalize(), string Normalize(System.Text... PadLeft Method string PadLeft(int totalWidth), string PadLeft(i... PadRight Method string PadRight(int totalWidth), string PadRight... Remove Method string Remove(int startIndex, int count), string... Replace Method string Replace(char oldChar, char newChar), stri... Split Method string[] Split(Params char[] separator), string[... StartsWith Method bool StartsWith(string value), bool StartsWith(s... Substring Method string Substring(int startIndex), string Substri... ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvid... ToByte Method byte IConvertible.ToByte(System.IFormatProvider ... ToChar Method char IConvertible.ToChar(System.IFormatProvider ... ToCharArray Method char[] ToCharArray(), char[] ToCharArray(int sta... ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatP... ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatPro... ToDouble Method double IConvertible.ToDouble(System.IFormatProvi... ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvide... ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider ... ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider... ToLower Method string ToLower(), string ToLower(cultureinfo cul... ToLowerInvariant Method string ToLowerInvariant() ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvide... ToSingle Method float IConvertible.ToSingle(System.IFormatProvid... ToString Method string ToString(), string ToString(System.IForma... ToType Method System.Object IConvertible.ToType(type conversio... ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvi... ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvi... ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvi... ToUpper Method string ToUpper(), string ToUpper(cultureinfo cul... ToUpperInvariant Method string ToUpperInvariant() Trim Method string Trim(Params char[] trimChars), string Trim() TrimEnd Method string TrimEnd(Params char[] trimChars) TrimStart Method string TrimStart(Params char[] trimChars) Chars ParameterizedProperty char Chars(int index) {get;} Length Property int Length {get;}
Ohoh, you see it ? If you look for the properties, or methods of an array containing Integers or Strings, you’ll list all theses members properties, but nothing about Arrays… Array is not an Array !
$Array -is [system.array]
If you want to get the members of an array, use the comma before the variable
,$Array | Get-Member
PS D:\> ,$Array | Get-Member TypeName : System.Collections.ArrayList Name MemberType Definition ---- ---------- ---------- Add Method int Add(System.Object value), int IList.Add(System... AddRange Method void AddRange(System.Collections.ICollection c) BinarySearch Method int BinarySearch(int index, int count, System.Obje... Clear Method void Clear(), void IList.Clear() Clone Method System.Object Clone(), System.Object ICloneable.Cl... Contains Method bool Contains(System.Object item), bool IList.Cont... CopyTo Method void CopyTo(array array), void CopyTo(array array,... Equals Method bool Equals(System.Object obj) GetEnumerator Method System.Collections.IEnumerator GetEnumerator(), Sy... GetHashCode Method int GetHashCode() GetRange Method System.Collections.ArrayList GetRange(int index, i... GetType Method type GetType() IndexOf Method int IndexOf(System.Object value), int IndexOf(Syst... Insert Method void Insert(int index, System.Object value), void ... InsertRange Method void InsertRange(int index, System.Collections.ICo... LastIndexOf Method int LastIndexOf(System.Object value), int LastInde... Remove Method void Remove(System.Object obj), void IList.Remove(... RemoveAt Method void RemoveAt(int index), void IList.RemoveAt(int ... RemoveRange Method void RemoveRange(int index, int count) Reverse Method void Reverse(), void Reverse(int index, int count) SetRange Method void SetRange(int index, System.Collections.IColle... Sort Method void Sort(), void Sort(System.Collections.ICompare... ToArray Method System.Object[] ToArray(), array ToArray(type type) ToString Method string ToString() TrimToSize Method void TrimToSize() Item ParameterizedProperty System.Object Item(int index) {get;set;} Capacity Property int Capacity {get;set;} Count Property int Count {get;} IsFixedSize Property bool IsFixedSize {get;} IsReadOnly Property bool IsReadOnly {get;} IsSynchronized Property bool IsSynchronized {get;} SyncRoot Property System.Object SyncRoot {get;}
Great this is what we were looking for.
Note that you can also do the following !
$Array = New-Object -typeName System.Collections.Arraylist Get-Member -InputObject $Array
If you want to know the hierarchie of an array (works also for any kind of variables)
#Quick array of Strings typed variables creation [String[]]$Array = "Galette","Saucisse","Rennes","Breizh"
Now let’s have a look about the hierarchie
$Array.pstypenames
System.String[] System.Array System.Object
Sort an array
Let’s play with the Sort method to start
$Array.Sort()
PS D:\> $Array.Sort() Exception lors de l'appel de «Sort» avec «0» argument(s): «Impossible de comparer deux éléments dans le tableau.» Au caractère Ligne:1 : 1 + $Array.Sort() + ~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : InvalidOperationException
You get an exception. It’s normal, you can’t use the Sort method in an array, where multiple datas types exist. By the way, if you still want to sort a multi typed array, PowerShell has (always) a solution. To sort an array of multi types, use the Sort-Object cmdlet !
$Array | Sort
PS D:\> $Array | Sort 1 2 3 Hourray!
Access elements of an array
If you want access specifics elements in an array.
PS D:\> $Array[3] Hourray!
You can also specify range
PS D:\> $Array[2..3] 3 Hourray!
And you can of course use a range and an unique index !
PS D:\> $Array[2..3 + 0] 3 Hourray! 1
Now you want to view access each elements
PS D:\> $Array | ForEach-Object { $_ } 1 2 3 Hourray!
If you want to confirm an array contains an item, you can also use the comparison operators:
- -Contains and -in whould be used for searching a specific element
- -match or -like to use a pattern to search
PS D:\> $array -contains "Hourray!" True
PS D:\> "Hourray!" -in $array True
PS D:\> $array -match "Hour" Hourray!
Add elements in an array
Adding elements to an array isn’t really difficult, the classical way is to use the Add method.
PS D:\> $Array.Add("PowerShell") 4 PS D:\> $Array 1 2 3 Hourray! PowerShell
Another way is to add full range of values
PS D:\> $array.AddRange(4..8) PS D:\> $array 1 2 3 Hourray! PowerShell 4 5 6 7 8
You can also add an array to another array.
PS D:\> [String[]]$TempArray = "Galette","Saucisse","Rennes" PS D:\> $NewArray = $Array + $TempArray PS P:\> $NewArray 1 2 3 Hourray! PowerShell 4 5 6 7 8 Galette Saucisse Rennes
Remove elements from an array
You can remove a set of elements using comparison operators and store the result in an array :p
PS D:\> $Array = "Galette","Saucisse","Rennes","Breizh" PS D:\> $Array Galette Saucisse Rennes Breizh PS D:\> $Array = $Array -notlike "*a*" PS D:\> $Array Rennes Breizh
pretty usefull isn’t it ?
You can of course remove a specific row from an array
PS D:\> $Array = New-Object System.Collections.ArrayList $Array.add(1) $Array.add(2) $Array.add(3) $Array.add("Hourray!") 0 1 2 3 PS D:\> $Array.RemoveAt(1) PS D:\> $Array 1 3 Hourray!
You can also remove a specific value from the array
PS D:\> $Array = New-Object System.Collections.ArrayList $Array.add(1) $Array.add(2) $Array.add(3) $Array.add("Hourray!") 0 1 2 3 PS D:\> $Array.Remove("Hourray!") PS D:\> $Array 1 2 3
Transform a string in an array
It’s very easy (it’s PowerShell) to transform a String in a complete array. To do this task we’ll use the Split() method available on string based objects…
PS C:\Users\fabie_000> cd c:\ PS C:\> $String = "Ambmcmdmemfmgmh" PS C:\> $Array = $String.split("m") PS C:\> $Array A b c d e f g h
Jagged arrays VS Multidimensional arrays
Both are usefull for holding lists of lists or arrays of arrays. Jagged is faster and use less memory than multidimensional, because it contains only the number of elements it needs. A non jagged array, is more like a matrix where every array must be the same size.
Here is how craete a jagged array.
PS D:\> $jagged = @(("A","B","C","D"),("X","Y","Z")) PS D:\> $jagged A B C D X Y Z PS D:\> $jagged[0][1] B PS D:\> $jagged[1][2] Z
And now, let’s have a look on multidimensional array. Let’s create a two dimension array.
PS D:\> $multi = New-Object 'object[,]' 10,20 # Add a value to case 1,5 and case 2,1 PS D:\> $multi[1,5] = "Hello" PS D:\> $multi[2,1] = "world" PS D:\> $multi Hello world PS D:\> $multi[1,5] Hello
If you wanted to create a three dimension array…
PS D:\> $multi = New-Object 'object[,,]' 10,15,20
Ok, i hope this article talks to you and you’ll use more and more arrays in your scripts 🙂
If you have any question about arrays, do not hesitate to ask in the comment part, also, if you find errors in this article say it !
Have a nice week end !
Regards
Hi Fabien!
Realy good Article!
I like to underline that the Komma IS THE OPERATOR TO CREATE ARRAYS in PowerShell.
(many PowerShell newbies are using the Komma by accident, to assign Arguments to Parameters)
So we have to make it very clear, that every time you use the Komma in PowerShell you create an Array!
Second I think we have to mention that the @() is even an Aperator to mark a even a Single Value as Array.
@(“Hello”) is an Array with one member.
Or you can create an Empty Array with this construct @().
With this you cann allways Query the count value even if the value is not an array.
If(@(‘Hello’).count -gt 0 ) { ‘do something!’}
greets Peter Kriegel
German PowerShell community
http://www.PowerShell-Group.eu
Hello Peter,
First of all, i’am a felow admirator or the German PowerShell community, great work with it !!
I agree about the @() constructor, i use it everyday to store objects an ouput them of my function
Function Do-Something {
Begin {
$Output = @()
}
Process {
1..10 | % {
$Output += New-Object PSCustomType -prop {“Name”=$_}
}
End {
$Output
}
}
I’ll add it to this article, it seems very legit
Thanks for pointing it !
Regards
Hi Fabien!
Really descriptive article.
I would like to point out another thing here is the use of -InputObject parameter with Get-Member.
Where you used
,$Array | Get-Member
to get the methods on the Array ..one could have also done the below:
$Array = New-Object -typeName System.Collections.Arraylist
Get-Member -InputObject $Array
🙂
You’re right Dexter, this is why i love PowerShell there are always many things to attain you goal 🙂
There is one more to mention 😉
An array is the candidate to NEVER use the + Plus operator to add Elements.
Even Removing Elements can do a performance hit!
See:
PowerShell Performance: The += Operator (and When to Avoid It)
http://powershell.org/wp/2013/09/16/powershell-performance-the-operator-and-when-to-avoid-it/
Adding and Removing Items from a PowerShell Array
http://www.jonathanmedd.net/2014/01/adding-and-removing-items-from-a-powershell-array.html
I personally use this construct to create an empty arraylist:
$ArrList = [System.Collections.ArrayList]@()
to bad that the PowerShell Team did not decided to use the Arraylist as defalt type. I think it has its reson.
greets Peter Kriegel
German PowerShell community
http://www.PowerShell-Group.eu