首页 > 解决方案 > Powershell通过正则表达式分割部分

问题描述

为了创建一个允许我执行防火墙迁移的脚本,我需要了解如何使用 Powershell 将输出拆分为多个部分。

防火墙(如果有帮助,它是一个 Sonicwall)产生一个输出,它由部分分隔。例如:

--System Information--
[Data]
--Network Interfaces--
[Data]
--User Objects Table--
[Data]
...

您可以看到输出由这些部分分隔,为此我生成了一个正则表达式:

$regex1='^--(\w*|\w+ \w+|\w+ \w+ \w+|\w+ \w+ \w+ \w+)--$'

但是,我不明白,我怎样才能产生一个输出来帮助我把特定的部分标题放在上面,数据直接放在下面。我不想要所有这些,只想要特定部分的特定输出。

任何帮助将非常感激,

非常感谢提前

标签: powershell

解决方案


在您的情况下,复杂的多行正则表达式可能有点多。一个非常简单的方法是逐行浏览内容:

$content = @"
--System Information--
[Data1]
--Network Interfaces--
[Data2]
[Data3]
--User Objects Table--
[Data4]
"@ -split [System.Environment]::NewLine

$dataDict = @{}
foreach ($line in $content)
{   
    # Each section opens a new entry in the $dataDict hash table.
    # Anything else that follows, gets added to this entry.
    if($line -match '^--(.+)--$')
    {
        $section = $Matches[1]
        $dataDict[$section] = @()
    }
    else 
    {
        $dataDict[$section] += $line
    }
}
# You can now narrow down the resulting object to the properties, 
# that you are interested in.
[pscustomobject]$dataDict | 
    Select-Object 'System Information', 'Network Interfaces' | 
    Format-List

推荐阅读