Loop and index help!

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Olaf Soyk Olaf Soyk 1 week, 6 days ago.

  • Author
    Posts
  • #66144
    Profile photo of Klas
    Klas
    Participant

    Hi!

    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:

    for($i=0;$i-lt$len;$i++){
    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...

    Anyone..?
    Help is MUCH appreciated! 🙂

  • #66147
    Profile photo of Olaf Soyk
    Olaf Soyk
    Participant

    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

    $Content[0,1]

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

    $Content[1]

    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.