【问题标题】:PowerShell Get-Content and replace object in a specific linePowerShell 获取内容并替换特定行中的对象
【发布时间】:2013-07-26 02:03:25
【问题描述】:

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

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

我希望有人能帮我解决这个问题。

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    如果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
    

    【讨论】:

    • 效果很好!我现在替换完整的行,愚蠢的我以前没有想到这一点。非常感谢! :)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2021-06-14
      • 2020-03-29
      • 2019-03-02
      • 2022-01-22
      相关资源
      最近更新 更多