Home > Back-end >  Cannot index into null array from function returned variable, or issues accessing regex data returne
Cannot index into null array from function returned variable, or issues accessing regex data returne

Time:12-17

I'm not sure if I'm returning the value from the function incorrectly, but when I try to access it's info, it has the above error,

Cannot index into a null array

I've tried a couple different ways, and I'm not sure if I'm not returning this correctly from the function, or if I'm just accessing the info returned incorrectly. Looking at Cannot index into null array, it looks like for him, some of his array had null values. But when I print my info to screen before I exit the function, it has info. How do I return the value found in the function such that I can loop through the contents in my main code and use one of the strings in the object? This is a continuation of parsing repeated pattern.

#parse data out of cpp code and loop through to further process
#function
Function Get-CaseContents{
  [cmdletbinding()]
  Param ( [string]$parsedCaseMethod, [string]$parseLinesGroupIndicator)
  Process
  {
     
     # construct regex
     $fullregex = [regex]"_stprintf[\s\S]*?_T\D*", # Start of error message, capture until digits
    "(?<sdkErr>\d )",       # Error number, digits only
    "\D[\s\S]*?",           # match anything, non-greedy
    "(?<sdkDesc>\((. ?)\))", # Error description, anything within parentheses, non-greedy
    "([\s\S]*?outError\s*=(?<sdkOutErr>\s[a-zA-Z_]*))", # Capture OutErr string and parse out part after underscore later
    "[\s\S]*?",             # match anything, non-greedy
    "(?<sdkSeverity>outSeverity\s*=\s[a-zA-Z_]*)", # Capture severity string and parse out part after underscore later
    '' -join ''
    
    # run the regex
    $Values = $parsedCaseMethod | Select-String -Pattern $fullregex -AllMatches

    # Convert Name-Value pairs to object properties
    $result = foreach ($match in $Values.Matches){
      [PSCustomObject][ordered]@{
        sdkErr      = $match.Groups['sdkErr']
        sdkDesc     = $match.Groups['sdkDesc']
        sdkOutErr   = $match.Groups['sdkOutErr']
        sdkSeverity = ($match.Groups['sdkSeverity'] -split '_')[-1] #take part after _
      }
    }

    #Write-Host "result:" $result -ForegroundColor Green
    $result
    return $Values
...

#main code
...
#call method to get case info (sdkErr, sdkDesc, sdkOutErr, sdkSeverity)
           $ValuesCase = Get-CaseContents -parsedCaseMethod $matchFound -parseLinesGroupIndicator "_stprintf" #need to get returned info back
           $result = foreach ($match in $ValuesCase.Matches){
              [PSCustomObject][ordered]@{
                sdkErr      = $match.Groups['sdkErr']
                sdkDesc     = $match.Groups['sdkDesc']
                sdkOutErr   = $match.Groups['sdkOutErr']
                sdkSeverity = ($match.Groups['sdkSeverity'] -split '_')[-1] #take part after _
              } #result
           } #foreach ValuesCase

The example of string sent to the function to parse is:

...
case kRESULT_STATUS_Undefined_Opcode:                       
            _stprintf( outDevStr, _T("8004 - (Comm. Err 04) - %s(Undefined Opcode)"), errorStr);
            outError    = INVALID_PARAM;
            outSeverity = CCA_WARNING;
            break;

        case kRESULT_STATUS_Comm_Timeout:                       
            _stprintf( outDevStr, _T("8005 - (Comm. Err 05) - %s(Timeout sending command)"), errorStr);
            outError    = INVALID_PARAM;
            outSeverity = CCA_WARNING;
            break;

        case kRESULT_STATUS_TXD_Failed:                     
            _stprintf( outDevStr, _T("8006 - (Comm. Err 06) - %s(TXD Failed--Send buffer overflow.)"), errorStr);
            outError    = INVALID_PARAM;
            outSeverity = CCA_WARNING;
            break;
...

Another thing I tried is (but it also had the index into null array issue):

foreach($matchRegex in $ValuesCase.Matches)
{
      $sdkOutErr   = $matchRegex.Groups['sdkOutErr']
      Write-Host sdkOutErr -ForegroundColor DarkMagenta
}

Ultimately, I need to grab $sdkOutErr to further process. I'll need to use the other variables too in the returned object, but this is the first one I need. I love the way the output is formatted in the function, but probably don't know how to return the info and use what is returned. I'm not sure what to search for to figure out the issue other than the error message, which leads me to believe I'm returning the info wrong. I don't think I need to return $result, because I think that's just a string with the values in the $values.Matches in the function. I need to access the values returned as I mentioned.

I checked, and the contents sent to the function is not blank.

I tried returning $results, and it looks like this when I write-Host, which would be difficult to access each sdkOutErr:

@{sdkErr=1000; sdkDesc=(Out of Memory); sdkOutErr= NO_MEMORY; sdkSeverity=FATAL} @{sdkErr=1002; sdkDesc=(Failed to load DLL); sdkOutErr= OTHER_ERROR; sdkSeverity=FATAL} @{sdkErr=1003; sdkDesc=(Failed to load DLL); sdk
OutErr= OTHER_ERROR; sdkSeverity=FATAL} @{sdkErr=1004; sdkDesc=(Failed to open); sdkOutErr= OTHER_ERROR; sdkSeverity=FATAL} @{sdkErr=1005; sdkDesc=(Unable to access the specified profile); sdkOutErr= OTHER_ERROR; sdkSeverity=
FATAL} @{sdkErr=100 ...

How can I return this from the function so that it's not a null array/index, and the data is accessible if I use a foreach loop (or two) in the main code to get the sdkOutErr (to start).

I'm fairly new to (complicated)powershell and I have a feeling I need a map inside the array in my function, but I'm not sure.

Before I returned the function Values or results, it was printing something like this out. Once I added in main $ValuesCase=Get-CaseContents... (returning $values from function), or $parsedCase = Get-CaseContents... (returning $results from function), it stopped showing this on the screen:

sdkErr sdkDesc                                                                                                                       sdkOutErr                                  sdkSeverity
------ -------                                                                                                                       ---------                                  -----------
1000   (Out of Memory)                                                                                                                NO_MEMORY                         FATAL      
1002   (Failed to load DLL)                                                                                                OTHER_ERROR                       FATAL      
1003   (Failed to load DLL)                                                                                             OTHER_ERROR                       FATAL      
1004   (Failed to open)                                                                                                      OTHER_ERROR                       FATAL  

CodePudding user response:

I tried returning $results, and it looks like this when I write-Host, which would be difficult to access each sdkOutErr:

Getting all the sdkOutErr values is not as difficult as you might imagine:

$results.sdkOutErr # this will output the `sdkOutErr` value from each object in the array

Or, outside the function:

(Get-CaseContents -parsedCaseMethod $matchFound -parseLinesGroupIndicator "_stprintf").sdkOutErr

Another option, which might perform better if the result set is large, is to use ForEach-Object to grab just the sdkOutErr values:

$fullResults = Get-CaseContents -parsedCaseMethod $matchFound -parseLinesGroupIndicator "_stprintf"
$sdkOutErrValuesOnly = $fullResults |ForEach-Object -MemberName sdkOutErr
  • Related