编写PowerShell脚本提取文本文件指定内容遇阻求助
PowerShell 按规则提取配置文件指定内容
问题
需要从配置文件中提取符合以下规则的内容:
- 先定位到包含
set name "Web Traffic Filter - General"的行,将其写入输出文件 - 之后收集每个
edit块里的set domain、set type、set action行,同样写入输出文件 - 重复直到文件结束
示例配置片段:
set name "Web Traffic Filter - General" config entries edit 2 set domain "*whois.com*" set type wildcard set action allow next edit 3 set domain "*lufthansa.com*" set type wildcard set action allow next
现有的脚本无法满足需求,会把所有匹配set domain/set type/set action的行都输出,而且还写错了目标策略名称(写成了Restricted):
foreach($line in Get-Content C:\Scripts\test.conf) { # Find Policy Name if($line -match 'set name "Web Traffic Filter - Restricted"'){ echo $line echo ############################################################ } # Find set domain if($line -match 'set domain'){ echo $line } # Find set type if($line -match 'set type'){ echo $line } # Find set action if($line -match 'set action'){ echo $line } }
解决办法
核心是通过两个状态变量跟踪上下文:是否已经找到目标策略名称,是否处于需要提取内容的edit块中。脚本如下:
# 目标策略名称,注意和需求保持一致 $targetPolicy = 'set name "Web Traffic Filter - General"' # 状态标记:是否已找到目标策略,是否在edit块内 $policyFound = $false $inEdit = $false # 输出文件路径,可自行修改 $outputFile = "C:\Scripts\filtered_config.conf" # 先清空输出文件(如果存在) if (Test-Path $outputFile) { Remove-Item $outputFile } Get-Content C:\Scripts\test.conf | ForEach-Object { $currentLine = $_.Trim() # 跳过空行,减少无效判断 if ([string]::IsNullOrWhiteSpace($currentLine)) { return } # 找到目标策略行,标记状态并写入文件 if ($currentLine -eq $targetPolicy) { $policyFound = $true Add-Content $outputFile $currentLine Add-Content $outputFile "############################################################" return } # 还没找到目标策略的话,直接跳过后续处理 if (-not $policyFound) { return } # 进入edit块,标记状态 if ($currentLine -match '^edit \d+$') { $inEdit = $true return } # 退出edit块,重置状态 if ($currentLine -eq 'next') { $inEdit = $false return } # 在edit块内,收集指定的配置行 if ($inEdit) { if ($currentLine -match '^set domain' -or $currentLine -match '^set type' -or $currentLine -match '^set action') { Add-Content $outputFile $currentLine } } }
脚本说明
- 状态跟踪:用
$policyFound控制是否开始处理后续内容,用$inEdit确保只提取edit块内的目标行,避免无关内容混入。 - 细节修正:原脚本里的目标策略名称写错了,已经修正为需求中的
Web Traffic Filter - General。 - 空行处理:先去除行首尾空白并跳过空行,避免空行干扰状态判断。
- 输出控制:找到目标策略后写入分隔线,每个
edit块内只收集需要的行,直接写入指定文件。
内容的提问来源于stack exchange,提问作者julianhaines
相关产品推荐
相关产品推荐

