Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

just starting to learn loops and arrays. i understand how to call a single variable in an array ie:

$animals = gc "c:\temp\animals.txt"
foreach ($animal in $animals)
{write-host "The"$animal "sleeps tonight."}

what i'm trying to figure out is how to call two different variables from two different arrays...ie:

$animals = gc "c:\temp\animals.txt"
$colors = gc "c:\temp\colors.txt"

this is the part where I'm confused. how do I call a foreach loop to cycle though both files simultaneously?

desired output: The white lion sleeps tonight, The black panther sleeps tonight, etc...

share|improve this question

2 Answers 2

up vote 1 down vote accepted

One way is to use arry indexing. Assuming both files have same line count:

$animals = gc c:\temp\animals.txt
$colors = gc c:\temp\colors.txt

for($i=0; $i -lt $animals.length; $i++)
{
    #print first line from animals  
    $animals[$i]

    #print first line from colors
    $colors[$i]
}
share|improve this answer
    
Thank you both for your suggestions. Shay, it looks like $i indicates the line number in the file. how does $i correlate with $animals.length? also, is there a help file on what that parameter ".length" is on the variable? How would one find out what it's used for and if there are any other parameters for a string value? One last thing, what is the -lt switch used for? less than? Other than that, the code works perfectly. Had to arrange it to fit my need but it does do the job. Thanks again Shay! –  user2385005 May 15 '13 at 9:42
    
Yes, $i refers to the line number. Length is a property of a collection (arrays) that indicates the number of objects in the collection. The best way to find what an object is capable of is to pipe it to the Get-Member cmdlet. -lt is the less than operator, you want the for statement to run as long as the current line number is less than the count of lines in the file (length). Remember that we start counting from 0. –  Shay Levy May 15 '13 at 9:55
    
thanks for the explanation Shay! Cheers. –  user2385005 May 15 '13 at 11:09

Assuming you have two text files (with same no. of entries) in C:\ you can write something like this -

$c = 0
$animal = Get-Content C:\Animal.txt

Get-Content C:\Color.txt | Foreach-Object{
    Write-Host "The $_ $($animal[$c]) sleeps at night"
    $c++
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.