Author Posts

March 10, 2017 at 9:07 pm

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! 🙂

March 10, 2017 at 10:34 pm

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