Loop and index help!

This topic contains 1 reply, has 2 voices, and was last updated by  Olaf Soyk 1 year ago.

  • Author
  • #66144



    I've "looped" through Google but can't find a solution to my problem.

    I have some txt files where I need to add line number 2 inside the text file whenever a condition is true.
    When some other conditions are met, I need to replace a substring in that line.
    I have found a way to get the line numbers' index, and a way to loop through the file.
    But my loop only checks if the whole string is correct and not the index of the string.

    My code is something like this:

    if($lines[$i] -in $indx1) {
    #do something
    } elseif ($lines[$i] -in $indx2) {
    #do something else
    } elseif ($lines[$i] -in $indx3) {
    #do something else
    } else {
    #do some other thing

    Since my $indx1 etc contains indexes and the $lines[$i] contains the whole string, the output is only the else-statement...

    Help is MUCH appreciated! 🙂

  • #66147

    Olaf Soyk

    Your question is a little vague but to acces the content of a file is easier than you probably think

    $Content = Get-Content -Path 'Path To Your File'

    Now you have the content in a variable and you can play with it


    this gives you the first 2 lines .... and guess what ...


    this gives you the second line and you can check whatever you have to check with it.
    If you need the rest of the file ...

    $Content[2..$($Content.count -1)]

    I hope that helps you a little

You must be logged in to reply to this topic.