1

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...

2 Answers 2

2

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]
}
Sign up to request clarification or add additional context in comments.

2 Comments

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!
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.
0

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++
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.