21
$a = @() 

How do I check if $a above is empty (which it is). I would like to get $true as answer.

2 Answers 2

37

That's not an associative array, it's a regular array, but the answer is the same. Use .Count and compare to 0.

An associative array is called a [hashtable] in PowerShell and its literal form uses @{} (curly braces).

@{}.Count -eq 0  # hashtable (associative array)
@().Count -eq 0  # array
Sign up to request clarification or add additional context in comments.

9 Comments

What's the protocol here; do we fix the title of the question?
@CharlieJoynt unclear; I don't know if the asker meant hashtable but wrote the syntax wrong, or wrote the correct syntax and the wrong title. I'm inclined to leave it for now unless the poster clarifies.
Trap for Young Players: Since PowerShell 3 introduced the synthetic Length property, I had assumed that I could always use Length and that any object with a Count property would have Count = Length. Not so for empty hash tables: @{}.Length is 1 while @{}.Count is 0.
@SimonTewsi yes, v3 added synthetic properties for both .Count and .Length, and they are equal, but they never override an existing property with the same name. So as a counter to your example, in a string it would be flipped: "".Count is 1, "".Length is 0. (5).Count and (5).Length are both 1. The purpose of the synthetic properties is so that you don't need to use conditionals to determine whether a variable contains an array or a single value. It makes a lot of patterns easier.
@briantist: So the synthetic Count and Length properties really have just a single use-case, to determine whether a variable is an array or a single value? And they're pretty much useless for anything else (eg string.Count and HashTable.Length suggest it would be dangerous to universally check Count and Length for variables of unknown data type)?
|
6

Arrays have Count property, and you can check if this value is 0. So the condition you would check for is

$a.Count -eq 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.