1

我有一个包含以下内容的文本文件:

Static Text MachineA MachineB MachineC
Just Another Line

第一行有两个静态单词(Static Text),中间有一个空格。这两个词后面有 0 个或多个计算机名称,也用空格分隔。

如果有 0 台计算机,但如果有 1 台或更多台计算机,我需要找到一种方法将文本添加到第一行(第二行不会改变)。我需要用新的计算机名称替换所有计算机名称。所以脚本应该编辑文件以获得如下内容:

Static Text MachineX MachineY
Just Another Line

我已经使用 Regex 查看了 -replace 函数,但无法弄清楚它为什么不起作用。这是我的脚本:

$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

我希望有人可以帮助我解决这个问题。

4

2 回答 2

3

如果Static Text没有出现在文件的其他地方,您可以简单地执行以下操作:

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

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

如果Static Text可以出现在其他地方,并且您只想替换第一行,则可以执行以下操作:

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

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

如果您只知道Static Text第一行中包含两个单词,但不知道它们究竟是哪些单词,那么这样的事情应该有效:

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

(Get-Content $OptionsFile) | % {
  if ($_.ReadCount -eq 1) {
    $_ -replace '^(\w+ \w+) .*', "`$1 $NewComputers"
  } else {
    $_
  }
} | Set-Content $OptionsFile
于 2013-07-24T11:41:17.617 回答
1

检查一行是否以“静态文本”开头,后跟一系列单词字符,并在匹配时返回您的字符串:

Get-Content $OptionsFile | foreach {    
  if($_ -match '^Static Text\s+(\w+\s)+')
  {
      'Static Text MachineX MachineY'
  }
  else
  {
      $_
  }
}
于 2013-07-24T11:13:51.140 回答