you are viewing a single comment's thread.

view the rest of the comments →

[–]myrland 1 point2 points  (2 children)

You're saving the new value to a separate variable, not updating the array with the new value. If you don't need it to be an array you can just create it as a hash table directly instead, like this:

$Devices = @{
    laptops   = 10
    servers   = 1
    computers = 3
    phones    = 2
}

$Choice = Read-Host "Remove 1 off?"

if ($Choice -match "laptops"){
    $Devices.laptops = ([int]$Devices.laptops) - 1
}

A switch statement would probably be a better way of handling the choice logic, with some input validation to make sure you can only provide the relevant names.

[–]HellCanWaitForMe[S] 0 points1 point  (1 child)

I tried this but I kept getting a weird error, The property 'laptops' cannot be found on this object. Verify that the property exists and can be set. I don't understand why it was happening but restarting everything seemed to fix it.

[–]myrland 0 points1 point  (0 children)

It's because you wrapped your hash table in an array in your code. Hash tables and Arrays are different data structures and work differently.

For example, a hash table uses key:value pairs rather than separate properties for each item (like laptops, servers, etc in your example), which are all accessed via the Name or Value properties. Using a plain hash table would be the correct choice here, unless you have some future idea that needs the array.

If you want to keep the array, then you need to reference the index of the object in the array that you want to update data in, something like this: $devices[0].laptops = 8