Arrays/Tables/Objects in Powershell

Christopher Jack 1,611 Reputation points
2021-03-24T16:51:51.43+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,361 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 29,571 Reputation points Microsoft Vendor
    2021-03-25T05:44:08.837+00:00

    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.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 44,776 Reputation points
    2021-03-24T18:31:07.873+00:00

    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++
        }
    
    1 person found this answer helpful.
    0 comments No comments