question

ChristopherJack-1763 avatar image
0 Votes"
ChristopherJack-1763 asked IanXue-MSFT answered

Arrays/Tables/Objects in Powershell

Hi,

I am slowly getting to grips with how to code in Powershell.


What I have noticed is

Arrays
You can add dynamically to an array using $array += "Hello"
You cannot however reference an index of an array without defining it first

Hash Tables
Hash Tables required unique values per row

If I was wanting to have

Ordernumber Position
123 2
123 56
645 1

Am i better having that as a Powershell object?
The add to it on the fly



windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
1 Vote"
IanXue-MSFT answered

Hi,

You may try an array of hash tables like below

 $array = @{123 = 2}, @{123 = 56}
 $array += @{645 = 1}

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
1 Vote"
RichMatheisen-8856 answered

A hash requires that each key is unique. There aren't any "rows" in a hash.

There's nothing to prevent you from having an array as the value associated with a key, though. Here's an example:

 $hash = @{}
 $position = 1
 1,2,1,3,4,2,6,5,3|
     ForEach-Object{
         if ($hash.ContainsKey($_)){
             $hash[$_] += $position  # add value to the array associated with the key
         }
         Else{
             $hash[$_] = ,$position  # create key in hash, set value to an array
         }
         $position++
     }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.