1

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Works great! I replace the complete line now, stupid I didn't thought of this before. Thanks a lot! :)
1

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
  {
      $_
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.