header1   header
header
header Register : : Login header
header
connector   connector
menuleft menuright
submenu   submenu
left
Determining which absolute element in an array you are working with
Last Post 14 Oct 2010 01:36 PM by Eric Morin. 3 Replies.
Printer Friendly
  •  
  •  
  •  
  •  
  •  
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
Eric MorinUser is Offline
New Member
New Member
Posts:36
Avatar

--
07 Sep 2010 01:24 PM
    I'm trying to figure out a way to determine which element in an array I am working with. Here's a simplified scenario:

    I've got a 2000 line text file, and I am iterating over each line using a foreach of an array of the file contents. If the text file meets certain criteria, I want to output the line and the array element, eg if it is the 40th line of the file, I want to output that line 40 (array item 39+1) contains the text. Obviously I can use a counter and increment it each time the loop starts, but it seems to me that there should be some way of having PowerShell tell me which array element I am working with.

    Any thoughts?
    Eric MorinUser is Offline
    New Member
    New Member
    Posts:36
    Avatar

    --
    21 Sep 2010 07:56 AM
    One-time bump
    George HowarthUser is Offline
    Basic Member
    Basic Member
    Posts:360
    Avatar

    --
    21 Sep 2010 11:51 AM

    You can use a for loop:

    $lines = Get-Content -Path "MyFile.txt"

    for ($i = 0; $i -lt $lines.Length; $i++)
    {
        Write-Host "Reading element $i ..."
       Write-Host $lines[$i]
    }

    Generally, use a for loop if you want to keep track of where you are in an array.

    Eric MorinUser is Offline
    New Member
    New Member
    Posts:36
    Avatar

    --
    14 Oct 2010 01:36 PM
    Here's what I found to do what I want:

    $a = 'a','b','c'
    [array]::IndexOf($a, 'b')

    This will return "2"

    You are not authorized to post a reply.


    Active Forums 4.3
    right
    footer   footer
    footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
    footer   footer