Powershell Pipeline masters

Tsvetkov, Martin 22 Reputation points
2021-06-27T14:02:31.57+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,628 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 122.6K Reputation points MVP Volunteer Moderator
    2021-06-27T14:35:38.667+00:00

    Hi @Anonymous ,

    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

    0 comments No comments

  2. Rich Matheisen 47,896 Reputation points
    2021-06-27T14:49:32.543+00:00

    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
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.