【问题标题】:PowerShell search for text and adding a linePowerShell 搜索文本并添加一行
【发布时间】:2018-07-31 19:14:29
【问题描述】:

抱歉,帖子太长了。想详细解释一下。 我正在努力实现三件事,而且非常接近。可能是小学生的错误。尝试了嵌套循环等,但无法正常工作。

看来我需要拆分$resultszone 数组。

  1. 在文件中搜索特定区域。在下面的示例中,它是\zones\、test1.in-addr.arpa、test2.in-addr.arpa 等之后的部分。
  2. 在找到区域后复制和修剪内容。在第一个示例中,只需 test1.in-addr.arpa(删除开头的“\”和结尾的“]”
  3. 在包含“类型”的行下方添加一行,包括找到的区域(例如 test1.in-addr.arpa)。

示例源文件:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS 服务器\Zones\test1.in-addr.arpa] “类型”=dword:00000001 "SecureSecondaries"=dword:00000002 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS 服务器\Zones\test2.in-addr.arpa] “类型”=dword:00000001 "SecureSecondaries"=dword:00000002

预期结果

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS 服务器\Zones\test1.in-addr.arpa] “类型”=dword:00000001 "DatabaseFile"="test1.in-addr.arpa.dns" "SecureSecondaries"=dword:00000002 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS 服务器\Zones\test2.in-addr.arpa] “类型”=dword:00000001 "DatabaseFile"="test2.in-addr.arpa.dns" "SecureSecondaries"=dword:00000002

我已经设法使用下面的代码实现了所有目标,除了它为每个部分添加了一行,包括来自找到的区域的所有结果。

例如:

"DatabaseFile"="test1.in-addr.arpa test2.in-addr.arpa
#Get FileName Path
$FileName = "C:\temp\test.conf"

#Search for pattern in file and trim to desired format.
#Store array in  $resultsZone
$resultszone = Select-String -Path "c:\temp\test.conf" -Pattern '(?<=Zones)(.*)' |
    select -expa matches |
    select -expa value |
    % { $_.Trim("\]") }

# Get contents of file
(Get-Content $FileName) | ForEach-Object {
    #Start Loop to find area of File to insert line
    $_ # send the current line to output
    if ($_ -match "type") {
        #Add Line after the selected pattern (type) including area trimmed
        """DatabaseFile" + """=""" + $resultszone + ".dns" + """"
    }
} | Set-Content C:\temp\elctest.conf

【问题讨论】:

  • 注册表文件使用 INI 格式,所以我建议这样解析。请使用页面顶部的搜索框。以前也有人问过类似的问题。
  • 仅用作第 3 方解决方案的输入。感谢您的意见。

标签: powershell


【解决方案1】:

我认为这可以实现您的目标:

$FileName = "C:\Temp\test.conf"

Get-Content $FileName | ForEach-Object {
    $Match = ($_ | Select-String -pattern '(?<=Zones\\)(.*)').matches.value

    if ($Match) { $LastMatch = ($Match).Trim("\]") }

    $_

    if ($LastMatch -and $_ -match 'type') {
        """DatabaseFile" + """=""" + $LastMatch + ".dns" + """"
    }
} | Set-Content C:\Temp\elctest.conf

修复方法是,我们在循环中对每一行执行Select-String,然后将匹配的时候存储在另一个变量中(名为$LastMatch),这样当我们到达我们想要插入前一次的行时它匹配,我们有它。

【讨论】:

  • 那是完美的马克。感谢您的努力和解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多