首页 > 解决方案 > 需要使用 powershell 从长配置文件中搜索一行

问题描述

简而言之,我需要在一个以“set ip”开头的长文件中找到一个特定的行,然后继续我需要替换的一些参数。此行在文件中出现多次,因此我需要在 2 个特定行之间找到它。

更长的故事:我们将很快为我们的办公室配置许多 FortiGate 防火墙,大多数设置、策略等将是相同的,但外部 IP 更改,其他一些地址更改等。所以我正在尝试制作一个 powershell脚本将采用现有配置(可能会更改)并找到我需要的特定行并替换它们。我尝试使用正则表达式,但无法让它在多行上为我工作。基本上作为参考,我需要在以下部分找到“set ip”:

config system interface
    edit "wan1"
        set vdom "root"
        set ip 7.7.7.7 255.255.255.252
        set allowaccess ping https ssh
        set ident-accept enable
        set type physical
        set scan-botnet-connections block
        set alias "WAN1"
        set role wan
        set snmp-index 1
    next

(为安全起见更改了IP)等等。到目前为止我得到的是:

get-content .\Fortigate.conf  | select-string -pattern "^#","set uuid " -notmatch

可悲的是,我没有尝试剪切那部分文本以仅在那里进行搜索。例如,我尝试使用正则表达式:

get-content .\Fortigate.conf  | select-string -pattern "^#","set uuid " -notmatch | select-string -Pattern '(?m)edit "wan1".*?end'

标签: regexpowershell

解决方案


对于这个问题,我不会尝试正则表达式多行,而是使用 PowerShell 方式“实现管道中间”并记住您所在的部分的信息,例如:

阅读每个特定的行(如果您编写 cmdlet,请使用process方法部分):

get-content .\Fortigate.conf  | ForEach {...

记住当前edit部分:

$Wan = ($_ | Select-String 'edit[\s]+"(.*)"').Matches.Groups[1].Value

set在 ( edit) 部分中捕获特定内容:

$SetIP = ($_ | Select-String 'set[\s]+ip[\s]+(.*)').Matches.Groups[1].Value

根据值和部分做出决定,例如:

If ($Wan -eq $MyWan) {
    if (($SetIP -Split "[\s]+") -Contains $MyIP) {...

将新的字符串条目(中间)放在管道上:

Write-Output "        set ip $MyNewIP"

或保留原始字符串条目:

Else {Write-Output $_}

推荐阅读