JustRonald
JustRonald

Reputation: 103

PowerShell Get-Content and replace object in a specific line

I have a text file with the following content:

Static Text MachineA MachineB MachineC
Just Another Line

The first line has two static words (Static Text) with a space between. After those two words there are 0 or more computer names, also seperated with a space.

I need to find a way to add text to the first line (second line does not change) if there are 0 computers but also if there is 1 or more computers. I need to replace all computer names with a new computer name. So the script should edit the file to get something like this:

Static Text MachineX MachineY
Just Another Line

I've looked at the -replace function with Regex but can't figure out why it is not working. This is the script I have:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

$content = Get-Content $OptionsFile
$content |
  ForEach-Object {  
    if ($_.ReadCount -eq 1) { 
      $_ -replace '\w+', $NewComputers
    } else { 
      $_ 
    }
  } | 
  Set-Content $OptionsFile

I hope someone can help me out with this.

Upvotes: 1

Views: 7906

Answers (2)

Shay Levy
Shay Levy

Reputation: 126732

Check if a line is starting with a 'Static Text ' followed by a sequence of word characters and return your string in case there a match:

Get-Content $OptionsFile | foreach {    
  if($_ -match '^Static Text\s+(\w+\s)+')
  {
      'Static Text MachineX MachineY'
  }
  else
  {
      $_
  }
}

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

If Static Text doesn't appear elsewhere in the file, you could simply do this:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

(Get-Content $OptionsFile) -replace '^(Static Text) .*', "`$1 $NewComputers" |
    Set-Content $OptionsFile

If Static Text can appear elsewhere, and you only want to replace the first line, you could do something like this:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

(Get-Content $OptionsFile) | % {
  if ($_.ReadCount -eq 1) {
    "Static Text $NewComputers"
  } else {
    $_
  }
} | Set-Content $OptionsFile

If you only know that Static Text consists of two words in the first line, but don't know which words exactly they'll be, something like this should work:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

(Get-Content $OptionsFile) | % {
  if ($_.ReadCount -eq 1) {
    $_ -replace '^(\w+ \w+) .*', "`$1 $NewComputers"
  } else {
    $_
  }
} | Set-Content $OptionsFile

Upvotes: 3

Related Questions