• PowerShell Arrays have me stumped

    Home » Forums » Developers, developers, developers » DevOps Lounge » PowerShell Arrays have me stumped

    Author
    Topic
    #492734

    Hey Y’all,

    Now I’ve been programming for decades and thought I had a good grasp of Arrays but PS has me stumped.:angry:
    Can someone tell me why I keep getting this error:

    Unable to index into an object of type
    System.Management.Automation.PSReference`1[System.Object[]].
    At line:18 char:8
    + $PathSegment[$SegCnt++] = $Result.value
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    [noparse] + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : CannotIndex[/noparse]

    Here’s the code:

    Code:
    Function Parse-Path {
      Param ( [Parameter(Mandatory=$True)]
              [ref]$PathSegment ,
              [Parameter(Mandatory=$True)]
                [string]$TestPath ,
              [Parameter(Mandatory=$False)]
               [string]$InclFN = $False
            )          
    
      
      $SegCnt = 0
      $PathRegX = [regex] "[0-9,A-Z,a-z,#,_,-, ]+||:"
      $Result = $PathRegX.match($TestPath)
    
      #$Result | Get-Member
    
      While ($Result.Success) {
           $PathSegment[$SegCnt++] = $Result.value  #Stmt causing Error!
           $Result = $Result.nextmatch()
      }   #End While Loop
    
      Return $SegCnt
    
    
    }  #End Function Parse-Path
    
    #Main
    
      Clear-Host
    
      $Elements = @(" "," "," "," "," "," "," "," "," "," "," ")
    
      $ArrCntr = Parse-Path -PathSegment ([ref]$Elements) `
                 -TestPath "G:BEKDocsExcelTestSkiPro Example_Revised#2.xlsm"
      write-host $Elements.GetType()
      write-host ""
      Write-Host "There are: $ArrCntr items."
      For ( $Cnt=1; $Cnt -lt $ArrCntr; $Cnt++) {
         Write-Host $Elements[$cnt]
      }
    

    I’ve tried declaring the $Elements array several different ways as well as using different indexing schemes. (This was originally a 2 dimensional array but I cut it back to one for simplicity…and still can’t get it to work.)

    Any insight would be most welcome. I’ve googled for 2 days now and can’t find the answer as all the hits show short command line examples rather that actual program segments that you can follow through. :cheers:

    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!
    Computer Specs

    Viewing 11 reply threads
    Author
    Replies
    • #1432542

      Ok, from someone who knows nothing about Powershell, so just dismiss me if you think I am writing gibberish.

      1. I see no $Elements array, did you mean $PathSegment?
      2. Is $PathSegment an array?

      Apologies if I am making you lose time.

      I always wanted to know a bit more about Powershell (even have a book), but time is usually so short…

    • #1432544

      And what if you used something like this (again, bear with me, any errors are my fault and my “who told you you could learn Powershell arrays with a few reads on your Powershell book” crash course:

      Code:
      While ($Result.Success) {
             [COLOR="#FF0000"]$PathSegment += $Result.value [/COLOR] 
             $Result = $Result.nextmatch()
             $SegCnt++
        }   #End While Loop
      
      
      • #1432549

        What if you do this? That will make $PathSegment an empty array, so the subsequent additions should work.

        Code:
        [COLOR="#FF0000"]$PathSegment = @()[/COLOR]
        
        While ($Result.Success) {
               [COLOR="#FF0000"]$PathSegment += $Result.value [/COLOR] 
               $Result = $Result.nextmatch()
               $SegCnt++
          }   #End While Loop
        
    • #1432545

      Rui,

      Been down that path:
      [noparse]Method invocation failed because
      [System.Management.Automation.PSReference`1[[System.Object[], mscorlib,
      Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]] does not
      contain a method named ‘op_Addition’.
      At line:19 char:8
      + $PathSegment += $Result.value
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (op_Addition:String) [], Runti
      meException
      + FullyQualifiedErrorId : MethodNotFound[/noparse]

      You don’t find $Elements in the Function because I’m passing it via Reference.

      Looks like we’re both in the same boat and I’m sure doing a lot of baling! 😆 :cheers:

      BTW: The code is self contained so you can copy it into the PS IDE and have at it.

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1432547

      Hmm… I would guess that result means your code is not interpreting the parameter as being an array.

    • #1432548

      Like Rui I too haven’t really got a clue. Where does the array definition occur? It’s simple in VBA, and in Perl it’s $variable for a scalar and %variable for an array. I think it’s similar in Ruby and Python (but I’m not familiar with those). It’s even simple in Fortran 66 and 72 (blimey that’s going back a few years). I’m not sure I want anything to do with PS if it’s this hard. I can’t even work out what your program’s doing (wot, no comments!).

      Did you mean PS ISE rather than IDE? It’s what I’ve got on my PC (Win 8.1)?

      Eliminate spare time: start programming PowerShell

    • #1432550

      I guess you need to declare the parameter as an array?

      Code:
      Function Parse-Path {
        Param ( [Parameter(Mandatory=$True)]
              [COLOR="#FF0000"]  [ref] [string[]]$PathSegment ,[/COLOR]
                [Parameter(Mandatory=$True)]
                  [string]$TestPath ,
                [Parameter(Mandatory=$False)]
                 [string]$InclFN = $False
              )          
      

      Of course, this will also mean your original way of indexing the variable should work, if this is the cause.

      P.S.: The Powershell books I own are not that good, organization wise. Hate when several examples declare parameters to be arrays but can’t see any explanation for that. This has been an exercise in uneducated guessing :rolleyes:.

    • #1432551

      Ok, this is as far as I’ve gone:

      Code:
      Function Parse-Path {
        Param ( [Parameter(Mandatory=$True)]
                [ref]$PathSegment ,
                [Parameter(Mandatory=$True)]
                  [string]$TestPath ,
                [Parameter(Mandatory=$False)]
                 [string]$InclFN = $False
              )          
      
        
        $SegCnt = 0
        $PathRegX = [regex] "[0-9,A-Z,a-z,#,_,-, ]+||:"
        $Result = $PathRegX.match($TestPath)
      
        #$Result | Get-Member
        $PathSegment = @()
      
        While ($Result.Success) {
             $Result = $Result.nextmatch()
             [COLOR="#FF0000"]$PathSegment.Value += $Result.value  [/COLOR]
            [COLOR="#FF0000"] $SegCnt++[/COLOR]
        }   #End While Loop
      
        Return $SegCnt
      
      
      }  #End Function Parse-Path
      
      #Main
      
        Clear-Host
      
        $Elements = @(" "," "," "," "," "," "," "," "," "," "," ")
      
        $ArrCntr = Parse-Path -PathSegment ([COLOR="#FF0000"][ref][/COLOR]$Elements) `
                   -TestPath "C:UsersRuiDocumentsebooksWindowsMicrosoft_Press_eBook_Programming_Windows_Store_Apps_2nd_Edition_2nd_Preview.pdf"
      
        write-host $Elements.GetType()
        write-host ""
        Write-Host "There are: $ArrCntr items."
        For ( $Cnt=1; $Cnt -lt $ArrCntr; $Cnt++) {
           Write-Host $Elements[$cnt]
        }
      

      No errors returned, count is shown to be 8, which seems correct, but nothing else is printed.

    • #1432558

      Rui,

      Been there done that bought the tee shirt! 😆
      I was actually there yesterday but couldn’t figure out why it wouldn’t output after returning to the main routine. :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1432563

      Seems Powershell doesn’t really like arrays as parameters passed by reference… I couldn’t find a reference that dealt with this in an intelligible manner. Sorry RG, hope your sort it, but I can’t go any further :(.

    • #1432590

      Rui,

      Thanks for trying. I’ve made some progress as I now have a one dimensional array version working.:fanfare:
      Of course I’m no longer passing by reference but it does work!

      Code:
      Function Parse-Path {
        Param ( [Parameter(Mandatory=$True)]
                  [string]$TestPath ,
                [Parameter(Mandatory=$False)]
                 [string]$InclFN = $False
              )          
      
        $Elements = New-Object 'object[]' 10
        $SegCnt = 0
        $PathRegX = [regex] "[0-9,A-Z,a-z,#,_,-, ]+||:"
        $Result = $PathRegX.match($TestPath)
      
        #$Result | Get-Member
      
        While ($Result.Success) {
             $SegCnt += 1
             $Elements[$SegCnt] = $Result.value
             $Result = $Result.nextmatch()
        }   #End While Loop
      
        $Elements[0] = $SegCnt
        Write-Host $Elements
        Return $Elements
      
      }  #End Function Parse-Path
      
      #Main
      
        Clear-Host
      
        $Elements = Parse-Path -TestPath "G:BEKDocsExcelTestSkiPro Example_Revised#2.xlsm"
        write-host $Elements, $Elements[0]
        write-host ""
        $ArrCntr = $Elements[0]
        Write-Host "There are: $ArrCntr items."
        For ( $Cnt=1; $Cnt -le $($ArrCntr); $Cnt++) {
           Write-Host $Elements[$Cnt]
        }
      

      Results:
      [noparse]
      6 G BEKDocs Excel Test SkiPro Example_Revised#2 xlsm
      6 G BEKDocs Excel Test SkiPro Example_Revised#2 xlsm 6

      There are: 6 items.
      G
      BEKDocs
      Excel
      Test
      SkiPro Example_Revised#2
      xlsm
      [/noparse]

      Next Steps:
      1. Get it to work with a 2 dimensional array.
      2. Get it to work with passing by reference (not as important any more since I went to it to solve a problem which doesn’t exist any more). :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1432595

      Well done :). This definitely seems not a very well documented situation. I confess I was a bit perplexed for the lack of easily found references on the issue.

    • #1432613

      Hey Y’all,

      Here’s a revised version with comments and usage examples.

      Code:
      Function Parse-Path {
      
        Param ( [Parameter(Mandatory=$True)]
                  [string]$TestPath 
              )          
      
        $Elements = New-Object 'object[]' 10
        $SegCnt = 0
        $PathRegX = [regex] "[0-9,A-Z,a-z,#,_,-, ]+||:"
        $Result = $PathRegX.match($TestPath)
       
        While ($Result.Success) {
             $Elements[++$SegCnt] = $Result.value
             $Result = $Result.nextmatch()
        }   #End While Loop
      
        $Elements[0] = $SegCnt
        Return $Elements
      
      }  #End Function Parse-Path
      
      #Main   Function Testing Code!
      
        Clear-Host
      
        $Elements = Parse-Path -TestPath "G:BEKDocsExcelTestSkiPro Example_Revised#2.xlsm"
        write-host $Elements, $Elements[0]
        write-host ""
        Write-Host "There are: $Elements[0] items."
      
        Write-Host "File Name: $($Elements[$Elements[0]-1]) `nFile Extension: $($Elements[$Elements[0]])`n"
        Write-Host $Elements[$Elements[0]-1] $Elements[$Elements[0]]
      
        For ( $Cnt=1; $Cnt -le $($Elements[0]); $Cnt++) {
           Write-Host $Elements[$Cnt]
        }
      

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    Viewing 11 reply threads
    Reply To: PowerShell Arrays have me stumped

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: