powershell:在特定行之前而不是之后附加文本

powershell: Append text before specific line instead of after

我正在寻找一种在行前添加文本的方法。 更具体地说,在一行和一个空白space之前。 现在,脚本会在 [companyusers] 行之后添加我的文本。 但我想在 [CompanytoEXT] 之前和 [CompanytoEXT].

上方的空白 space 之前添加这一行

有人知道怎么做吗?

我想做的事情的视觉表示:https://imgur.com/a/lgH5i

我当前的脚本:

$FileName = "C:\temptest\testimport - Copy.txt"
$Pattern = "[[\]]Companyusers"  
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @() 
Foreach ($Line in $FileOriginal)
{   
    $FileModified += $Line
    if ($Line -match $pattern) 
    {
        #Add Lines after the selected pattern 
        $FileModified += "NEWEMAILADDRESS"

    } 
    }

Set-Content $fileName $FileModified

感谢任何建议!

即使您只是指出我在哪里寻找答案,我们也将不胜感激。

使用 ArrayList 可能更容易,这样您就可以在特定点轻松插入新数据:

$FileName = "C:\temptest\testimport - Copy.txt"
$Pattern = "[[\]]Companyusers"
[System.Collections.ArrayList]$file = Get-Content $FileName
$insert = @()

for ($i=0; $i -lt $file.count; $i++) {
  if ($file[$i] -match $pattern) {
    $insert += $i-1 #Record the position of the line before this one
  }
}

#Now loop the recorded array positions and insert the new text
$insert | Sort-Object -Descending | ForEach-Object { $file.insert($_,"NEWEMAILADDRESS") }

Set-Content $FileName $file

首先将文件打开到 ArrayList 中,然后对其进行循环。每次遇到该模式时,您可以将前一个位置添加到一个单独的数组中,$insert。循环完成后,您可以循环 $insert 数组中的位置,并使用它们将文本添加到 ArrayList 中。

这里你需要一个小状态机。当您找到正确的部分时请注意,但不要插入该行。仅在下一个空行(或文件末尾,如果该部分是文件中的最后一个部分)插入。

还没有测试过,但应该是这样的:

$FileName = "C:\temptest\testimport - Copy.txt"
$Pattern = "[[\]]Companyusers"  
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @() 

$inCompanyUsersSection = $false

Foreach ($Line in $FileOriginal)
{   
    if ($Line -match $pattern) 
    {
        $inCompanyUsersSection = $true
    }

    if ($inCompanyUsersSection -and $line.Trim() -eq "")
    {
        $FileModified += "NEWEMAILADDRESS"
        $inCompanyUsersSection = $false
    } 

    $FileModified += $Line
}

# Border case: CompanyUsers might be the last sction in the file
if ($inCompanyUsersSection)
{
    $FileModified += "NEWEMAILADDRESS"
} 

Set-Content $fileName $FileModified

编辑:如果您不想使用 "insert at the next empty line" 方法,因为您的部分可能包含空行,您也可以在下一节的开头触发插入 ($line.StartsWith("[")).然而,这会使事情变得复杂,因为现在你必须向前看两行,这意味着你必须在写出之前缓冲一行。可行但丑陋。