1

This is a basic question but I'm stuck. I have the below code:

$array = @(
    $hashtable1 = @{
        Name = "Test1"
        Path = "C:\Test1"
    }
    $hashtable2 = @{
        Name = "Test1"
        Path = "C:\Test1"
    }
)

The array is created but empty. I have tried comma separation:

$hashtable1 = @{}, $hashtable2 = @{}

But this did not work. What is wrong?

2 Answers 2

3

You are assigning the hashtables as variables. Take out the variable assignment:

$array = @(
    @{
        Name = "Test1"
        Path = "C:\Test1"
    },
    @{
        Name = "Test1"
        Path = "C:\Test1"
    }
)
Sign up to request clarification or add additional context in comments.

Comments

1

gms0ulman's helpful answer provides an effective solution for constructing your array of hashtables.

To provide some background information:

  • A variable assignment such as $hashtable1 = ... is not an expression, so it produces no output, which is why your $array = assignment ended up containing an empty array, given that @(...) saw no output.

  • However, you can make assignment statements produce output simply by enclosing them in (...), which turns them into expressions, which allows you to assign to the variable and output the assigned value.

  • @(...) is not needed to construct arrays; instead, you can use ,, the array-construction operator.

Even though it may not be needed, the following demonstrates how to both construct the array of hashtables and save the individual hashtables in dedicated variables:

$array =
  ($hashtable1 = @{
      Name = "Test1"
      Path = "C:\Test1"
  }),
  ($hashtable2 = @{
      Name = "Test1"
      Path = "C:\Test1"
  })

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.