需要使用 powershell 从长配置文件中搜索一行



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

长话短说: 我们很快就会为我们的办公室配置许多FortiGate防火墙,大多数设置,策略等将是相同的,但外部IP会更改,其他一些地址会更改等。 所以我正在尝试制作一个 powershell 脚本,该脚本将采用现有的配置(可能会更改(并找到我需要的特定行并替换它们。 我尝试使用正则表达式,但无法让它在多行上为我工作。 基本上作为参考,我需要在以下部分找到"设置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'

对于这个问题,我不会尝试正则表达式多行,而是以 PowerShell 方式"为管道中间实现">来处理它,并记住您在哪个部分的信息,例如:

读取每个特定行(如果编写 cmdlet,请使用"process方法"部分(:

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

请记住当前的edit部分:

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

在(edit(部分中捕获特定set

$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 $_}

最新更新