question

MartinTsvetkov-3013 avatar image
0 Votes"
MartinTsvetkov-3013 asked MotoX80 commented

Powershell Pipeline masters

Hi. I want all that lines to pipeline

$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] += $textToAdd
$fileContent | Set-Content $filePath

I tried for hours w/o success
Anybody...

windows-server-powershell
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I think that you need to explain what is in $lineNumber and what you are trying to accomplish.

Are you trying to append a line to the file?
Replace the last line?
Replace a line somewhere within the file?
Insert a line somewhere within the file?

Are you getting an error?

0 Votes 0 ·
AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered AndreasBaumgarten edited

Hi @MartinTsvetkov-3013,

I am not sure what is the expected outcome.

Maybe this helps:

 $filepath = "Junk/someText.txt"
 $textToAdd = "Just a test with pipe"
 ((Get-Content -Path $filepath)[$linenumber - 1]) + $textToAdd | Set-Content -Path $filepath


(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

Regards
Andreas Baumgarten

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered

It's unlikely you'd be able to do what you want. Firstly because the file you're trying to modify would still be in use by the Get-Content cmdlet. Secondly because you'd have no idea how many lines are in the file until you reached the end.

Something like this might work for you:

 $filepath = "c:\junk\cr.txt"
 $textToAdd = "A","B"
 $currentline = 0
 [array]$fileContent = Get-Content $filePath
 $lineNumber = $filecontent.count - 1
 $filecontent |
     ForEach-Object{
         if ($currentline -eq $linenumber)
         {
             $textToAdd
         }
         $_
         $currentline++
     } | Set-Content $filePath
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.