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  | ------ |   
+--------+--------+--------+--------+
0

1 Answer 1

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'
)
Sign up to request clarification or add additional context in comments.

6 Comments

might need to replace the , with ; between Serv1 and Serv2 when creating $hash
Good call @AnthonyStringer, better yet, no separator needed with newline.
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?
@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')
For any other readers, I found an incredibly insightful discussion and answer chain here: stackoverflow.com/questions/226596/…
|

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.