Search code examples
powershellordered-map

Missing property name after reference operator


I have a map, that is originally c++ code, file read, and parsed into a map. The original code was an enum, and didn't have values for all items. $fileContent:

enum{
    Error_A = 110,    
    Error_B,               
    Error_C,               
    Error_D,             
    Error_E,             
    Error_F,          
    Error_G = 118,  
...
};    

I have read the file contents and put it in a map like this (works fine):

  function Get-Contents_b{
    [cmdletbinding()]
    Param ([string]$fileContent)

            #Error_AA = 20
  
    # create an ordered hashtable to store the results
    $errorMap = [ordered]@{}
    # process the lines one-by-one
    switch -Regex ($fileContent -split '\r?\n') {
      '^[\s]*([\w]+)[\s=]*([-\d]*)' { # Error...=12345
        $key,$value = ($matches[1,2])|ForEach-Object Trim
        $errorMap[$key] = $value
    }
  }
...

Then I want to iterate over the map, and for the ones with enum values dependent on single digit increase from the previous, I want to assign the value of the previous value plus one. I'm trying to do that below, but getting the $previousKey, using $key-1, and then getting the value from that, is giving the error shown in the comment.

  foreach ($key in $errorMap.$keys)
  {
      $previousKey = $errorMap.[($key-1)]  #missing property name after the reference operator
      Write-Host $errorMap.$previousKey
      if(($errorMap.$key).Value = "")
      {
        $errorMap.$key.Value = $errorMap.$previousKey.Value + 1
      }
  }

Any ideas how to fix this or get the previous value and assign the next empty value the previous value plus one?

This is with powershell 5.1 and VSCode.


Solution

  • You're mistakenly mixing member (property) access via the . operator with indexed access via [...] - you must use one or the other.

    However, what you want is positional access to your keys (which only works with an ordered hashtable):

    foreach ($keyIndex in 0..($errorMap.Count-1))
    {
      if ('' -eq $errorMap[$keyIndex]) {
        $previousValue = $errorMap[$keyIndex - 1] 
        Write-Host $previousValue
        $errorMap[$keyIndex] = 1 + $previousValue
      }
    }