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...
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...
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?
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
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
11 people are following this question.