Nizuru
Nizuru

Reputation: 23

Append contents to end of file at end of each nested loop iteration?

$words = Get-Content D:\words.txt
$row = Get-Content D:\row.txt
$j=0

 Get-Content D:\row.txt | ForEach-Object {
    for ($i = 0; $i -lt $words.Count; $i++){
   Write-Host ($row.Getvalue($j)+ ". " + $words.GetValue($i))
   }
   $j++
   Write-Host ("`n")
} | Set-Content D:\rip.txt

*OUTPUT*
1. alpha
1. beta
1. charlie
1. delta


2. alpha
2. beta
2. charlie
2. delta


3. alpha
3. beta
3. charlie
3. delta


4. alpha
4. beta
4. charlie
4. delta

I wanted to save all the contents of the nested loop into a rip.txt, however it does not save properly. Either there are no contents inside the file or only the 1st row of contents are saved to a file

1. alpha
1. beta
1. charlie
1. delta

Upvotes: 1

Views: 25

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60518

Your code can be reduced to this:

$words = Get-Content D:\words.txt
Get-Content D:\row.txt | ForEach-Object {
    foreach($word in $words) {
        "$_. $word"
    }
    "`n"
} | Set-Content D:\rip.txt

The main issue is the use of Write-Host which writes to the Information Stream not to the Success Stream.

Upvotes: 1

Related Questions