PowerShell: Working With Arrays

Problem: elements of a System.Array couldn’t be counted

# Example output when an object is a Hashtable type
PS C:\Users\tola> $arr.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object

Resolution: convert a Hashtable to an Array type

# Perform explicit casting
PS C:\Users\tola> $x=[Array]$arr

# Example output when an object is an Array type
PS C:\Users\tola> $arr.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

# Validate that the casting has succeeded
PS C:\Users\tola> $x.gettype()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

# Since System Array type can contain objects, its elements can be counted
PS C:\Users\tola> $x.count
1

Leave a Reply

Your email address will not be published. Required fields are marked *