简体   繁体   中英

Powershell Nested foreach loop with multiple arrays

I have two files "name.txt" and "path.txt, contents for each file are below:

name.txt:

John
Mike
Paul

path.txt:

C:\directory\john.config
C:\directory\mike.config
C:\directory\paul.config

I want to print n'th line from each file together

Code:

$name = Get-Content "C:\path\name.txt"
$path = Get-Content "C:\path\path.txt"
foreach($var1 in $name){
foreach($var2 in $name){
Write-Host "$name - $path
}
}

Desired output:

John - C:\directory\john.config
Mike - C:\directory\mike.config
Paul - C:\directory\paul.config

My Output:

John - C:\directory\john.config C:\directory\mike.config 
C:\directory\paul.config
Mike - C:\directory\john.config C:\directory\mike.config 
C:\directory\paul.config
Paul - C:\directory\john.config C:\directory\mike.config 
C:\directory\paul.config

I want to get the desired output, can anyone please help me how I can get the desired output?

This will work but without knowing a bit more about what you are trying to achieve it's difficult to tell whether it is a sensible solution or not.

$names = ( Get-Content -Path 'C:\temp\name.txt' )
$paths = ( Get-Content -Path 'C:\temp\path.txt' )
for($i = 0; $i -lt $names.Length; $i++) {
    Write-Host ( '{0} - {1}' -f $names[$i], $paths[$i] )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM