首页 > 解决方案 > PS:从文本文件创建多维数组 - Cisco Switch Config

问题描述

我正在尝试创建一个脚本来处理多个 cisco 配置并通过 CSV 将它们移植到 Excel,其中包含以下字段:接口名称、描述、VLAN 和语音 VLAN。

我可以使用以下代码导入配置文件:

$importPath = ["PATH TO FILE"]
$text = Get-Content -path $importFile

然后我可以处理导入的文本以将接口组合在一起,如下所示:

$regex = '(?ms)interface(.+?)!'
$text = $text -join "`n"
$matchedGroups = $text | Select-String $regex -AllMatches | ForEach-Object { $_.Matches.Value }

生成的文本现在按界面分组(其中有一些垃圾,但它很少且易于管理)。但是,我不知道如何获取这些组(字符串行)并将它们组织在一个数组中,其中每行都是数组中的一个元素。一旦我有了这个,我就可以为净化和提取的信息分配标签(如上)。$matchedGroups 变量中的文本示例:

PS: C:\$matchedGroups[0]
interface Port-channel1
 description Port-channel1 to DEVICE
 switchport access vlan ####
 switchport trunk native vlan ####
 switchport mode trunk

所需的数组示例:

$array = @("interface Port-channel1"," description Port-channel1 to DEVICE"," switchport access vlan ####"," switchport trunk native vlan ####"," switchport mode trunk")

标签: powershell

解决方案


试试这个

$array =$matchedGroups[0] -split "`n"

#print first element
$array[0]

如果你想修剪你的行:

$array=$string -split "`n" |%{$_.trim()}

推荐阅读