Joe
Joe

Reputation: 33

Powershell How to get if statement in a foreach loop to variable

How do you get an if statement output in a foreach loop to a variable?

Has 2 text files with pc names in

```
$Test1 = Get-Content -Path C:\temp\test.txt

$test2 = Get-Content -Path C:\temp\test2.txt

foreach ($item1 in $Test1)
{

    foreach ($item2 in $test2)
    {
        if ( $item1 -eq $item2) 
        {
            Write-output $item1            
        }


    }

}

```

I can see all the pc names from Write-output but $item1 has only the last pc name

Upvotes: 0

Views: 1395

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

PowerShell allows you to capture the cumulative output from any flow control statement using a simple assignment (=):

$Test1 = Get-Content -Path C:\temp\test.txt
$test2 = Get-Content -Path C:\temp\test2.txt

foreach ($item1 in $Test1)
{
    foreach ($item2 in $test2)
    {
        $outputFromIf = if ($item1 -eq $item2) 
        {
            Write-output $item1            
        }
    }
}

In your case - assuming you're expecting to find multiple matches - assigning the output from if(){...} will overwrite the value of $outputFromIf on every iteration, so you'll probably want to capture the output from the outer loop instead:

$outputFromLoop = foreach ($item1 in $Test1)
{
    foreach ($item2 in $test2)
    {
        if ($item1 -eq $item2) 
        {
            Write-output $item1            
        }
    }
}

Now $outputFromLoop will contain any output emitted from inside the outer foreach($item1 in $Test1){ ... } loop.

Upvotes: 4

Related Questions