I’ve seen lots of methods for checking whether or not a variable in Powershell contains an array. All of them work, so really it comes down to which one is the easiest. Some cmdlets and constructs will error out if you treat them like an array, or more commonly, produce unexpected results. Here are the two methods I’ve used for this over the years, I’ll let you be the judge of which one is the easiest.
Method 1: Using the ‘-is’ operator
1 2 3 4 5 6 7 8 |
# Declare an array $a = @(1,2,3) # Declare a string $b = "Not an array" $a -is [System.Array] # True $b -is [System.Array] # False |
Method 2: Using the Count property
1 2 3 4 5 6 7 8 |
# Declare an array $a = @(1,2,3) # Declare a string $b = "Not an array" $a.Count -gt 1 # True $b.Count -gt 1 # False |
Hope this helps make your code a little cleaner and remember; the next data you validate, could be yours. Happy scripting!