0

I need a datatype for the PowerShell to add different values to a key. which type should I choose?

The data are like:

+--------+--------+--------+--------+   
| Serv1  | Serv2  | Serv3  | Serv4  |   
| -------+--------+--------+------- |    
| User1  | User2  | User3  | User4  |   
| User3  | User1  | User2  | User4  |   
| User7  | User8  | User9  | ------ |   
+--------+--------+--------+--------+
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
SUT
  • 323
  • 1
  • 3
  • 14

1 Answers1

5

This would be easier to answer with more information. But based on that, it looks like a [hashtable] where the values are arrays is what you want.

Example:

$hash = @{
    Serv1 = @(
        'User1',
        'User3',
        'User7'
    )

    Serv2 = @(
        'User2',
        'User1'
    )
}

# add a new user to an existing key

$hash.Serv2 += 'User8'

# add a new key

$hash.Serv3 = @(
    'User3',
    'User2'
)
briantist
  • 45,546
  • 6
  • 82
  • 127
  • might need to replace the `,` with `;` between Serv1 and Serv2 when creating $hash – Anthony Stringer Apr 06 '16 at 17:01
  • 3
    Good call @AnthonyStringer, better yet, no separator needed with newline. – briantist Apr 06 '16 at 17:01
  • I've been on the fence about using the += operator in powershell since I'm mindful about resource usage when upscaling scripts. From what I (currently) understand, you're reallocating memory and recreating the hashtable every time you do a += ; Is this how powershell handles this? – Chris Kuperstein Apr 06 '16 at 17:37
  • @ChrisKuperstein i believe this is only noticeable in larger arrays, but if you wanted to, you could replace all three of the `@(` with `[System.Collections.ArrayList](` and replace `$hash.Serv2 += 'User8'` with `[void]$hash.Serv2.Add('User8')` – Anthony Stringer Apr 06 '16 at 17:52
  • @AnthonyStringer That's what I thought. I always think big-scale since I work over 550~ servers so these little things matter to me, and I'm sure other readers down the line. I still use += when I know what I'm working with is small and negligible, but in this case of storing arraylists in a hashtable, using `.Add()` is probably best for the scenario in the long run. – Chris Kuperstein Apr 06 '16 at 18:01
  • 1
    For any other readers, I found an incredibly insightful discussion and answer chain here: http://stackoverflow.com/questions/226596/powershell-array-initialization – Chris Kuperstein Apr 06 '16 at 18:02