Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Now I use get-content to get the file's content, I need to edit some of the lines. For example, change the 2nd line:


line2: hello Everyone!


line2: Hello Mr. Brown!

Which cmdlet can I use?

share|improve this question
up vote 1 down vote accepted
$file = Get-Content myfile.txt
$file | ForEach-Object { 
    if ($_.ReadCount 2) { 
      $_ -replace '\w+','Hello Mr. Brown!' 
    } else { 
  } | 
  Set-Content myfile.txt

This will alter the whole line (specified in ReadCount)to Hello Mr. Brown!. Be sure to use PowerShell 2.0+.

share|improve this answer
Thanks very much! – pansal Nov 10 '11 at 2:44

If the content is sufficiently unique a replace applied to all lines (but will only match the one you are interested in).

Otherwise load the whole file into a collection, and update the second element (index one).

If the file is large enough that loading the whole file into memory at once is an issue, then something more clever will be needed ….

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.