Home > Net >  ADD Dictionary to List. In Funtion: $user_list.add("user3", $user_name), I must type in &q
ADD Dictionary to List. In Funtion: $user_list.add("user3", $user_name), I must type in &q

Time:03-25

$user_list = @{
user1 = [ordered]@{
    properties = ("666-555-2345", "1234 E Main St", "Dodge Charger"); 
    misc_data = 34145}
user2 = [ordered]@{
    properties = ("666-555-1234", "5678 N Elm St", "Plymouth Dart"); 
    misc_data = 46112}
}

function add_new_user($user_name, $info, $misc){
    $user_name = [ordered]@{
        properties = $info; 
        misc_data = $misc}
    $user_list.add(**"user3"**, $user_name)
}

add_new_user user3 ("666-555-1357", "9876 S Oak Rd", "Chevy PT Cruiser") 33879

$user_list

NOTE: This is a function, so it is not practical to actually type "User#" (within the function) for each new user.

I do not know how to make it take the passed variable for that first value of .ADD.

$user_list.add("user3", $user_name) = $user_list.add("user3", $user_name)

$user_list.add($user_name, $user_name) = $user_list.add($user_name, $user_name)

CodePudding user response:

You can update your hash table from your function like this:

$user_list = @{
    user1 = [ordered]@{
        properties = "666-555-2345", "1234 E Main St", "Dodge Charger"
        misc_data = 34145
    }
    user2 = [ordered]@{
        properties = "666-555-1234", "5678 N Elm St", "Plymouth Dart"
        misc_data = 46112
    }
}

function add_new_user($user_name, $info, $misc) {
    if($user_list.ContainsKey($user_name)) {
        return "$user_name already exists in `$userList"
    }
    $user_list[$user_name] = [ordered]@{
        properties = $info
        misc_data = $misc
    }
}

I have added a condition to check if the user is already there so that instead of replacing the key / value pair it would return the message that the user already exists.

If you test it you would see the following:

PS /> add_new_user user3 ("666-555-1357", "9876 S Oak Rd", "Chevy PT Cruiser") 33879
PS /> $user_list

Name                           Value
----                           -----
user1                          {properties, misc_data}
user3                          {properties, misc_data}
user2                          {properties, misc_data}

PS /> add_new_user user2 ("666-555-1357", "9876 S Oak Rd", "Chevy PT Cruiser") 33879

user2 already exists in $userList
  • Related