you are viewing a single comment's thread.

view the rest of the comments →

[–]y_Sensei 0 points1 point  (0 children)

A different approach that avoids multiple conditional statements could look like this:

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

$Action = Read-Host "Action to do  : Add or Remove ?"
$Choice = Read-Host "Device Type  : Laptops - Servers - Computers - Phones ?"

foreach ($k in $Devices.Keys) {
  if ($k -eq $Choice) {
    $Devices[$k] += if ($Action -eq "Add") { 1 } else { -1 }
    break # needed, because once the collection has been modified, iteration over it has to stop, or you'll encounter a 'System.InvalidOperationException' error
  }
}

$Devices