powershell - Powershell通过正则表达式分割部分
问题描述
为了创建一个允许我执行防火墙迁移的脚本,我需要了解如何使用 Powershell 将输出拆分为多个部分。
防火墙(如果有帮助,它是一个 Sonicwall)产生一个输出,它由部分分隔。例如:
--System Information--
[Data]
--Network Interfaces--
[Data]
--User Objects Table--
[Data]
...
您可以看到输出由这些部分分隔,为此我生成了一个正则表达式:
$regex1='^--(\w*|\w+ \w+|\w+ \w+ \w+|\w+ \w+ \w+ \w+)--$'
但是,我不明白,我怎样才能产生一个输出来帮助我把特定的部分标题放在上面,数据直接放在下面。我不想要所有这些,只想要特定部分的特定输出。
任何帮助将非常感激,
非常感谢提前
解决方案
在您的情况下,复杂的多行正则表达式可能有点多。一个非常简单的方法是逐行浏览内容:
$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
推荐阅读
- azure-web-app-service - 是什么触发了 WEBJOBS_SHUTDOWN_FILE 的创建?
- mysql - MySQL JSON_EXTRACT 在嵌套级别具有动态键名
- javascript - 如何在嵌套对象中搜索值并检索父值?
- nlp - 如何解决与 zstandard 中使用的帧相关的错误,它需要太多内存来解码
- visual-studio-code - 更改 VS Code 调试操作(重启按钮)
- javascript - 原子异步/等待调用 - 如果第二个失败,是否可以不先执行?
- ibm-mq - Apache qpid 客户端到 IBM MQ Broker v 9.1.0.6 + 请求 - 使用队列的回复模式,不起作用
- signalr - SignalR Websocket 未收到消息
- javascript - 正则表达式的编辑
- angular - Nativescript Image-picker 在外部存储中找不到文件