1

I have a super easy one here but I cannot figure it out and driving me insane. I suspect it is some kind of scoping issue of the variable (global, etc.?)

Anyway, here is my code:

$i = 0
foreach ($line in Get-Content 'somefile.txt') {

    if ($i = 1) {
        echo "$i Line: $line"
    }
    $i++
    // I even tried $i = $i + 1
}

Output is $1 = 1 always. It doesn't seem to count.

How can I fix this?

1
  • = is an assignment, to compare use if ( $i -eq 1){ Commented Aug 13, 2018 at 8:58

2 Answers 2

2

$i = 1 assigns 1 to $i, so the result is always 1.

You need to use -eq: if ($i -eq 1) ...

See Get-Help about_comparison_operators for more information.

Sign up to request clarification or add additional context in comments.

Comments

1

Your question isn't clear, but it looks like you're trying to output each line of your text file with the line number prepended. If so, one way to do it is:

Get-Content 'somefile.txt' |
    ForEach-Object {$i = 0}{
        "$i Line: $_"
        $i++
    }

4 Comments

Yeah pretty much what I want to do. Ideally only show certain lines that match a number. Still not sure why my code fails to increment a simple variable.
@GrahamSmart it doesn't fail to increment, you are setting it back to 1 every time the loop runs
How am i?? I dont see that as the declaration is outside of the loop?
I hate PS ;) thanks guys! , boxdog your code worked wonders too !

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.