powershell - Selecting Text In between strings
问题描述
I am trying to parse some text between strings of output.
I've tried using -split and substring but I am not getting the correct output
Here are the input file/Pipeline values
Please remove the following Roles:
Role1
Role2
Please remove the following Groups:
Groups1
Groups2
Please remove the following Profiles:
Profiles1
Profiles3
Profiles8
Please remove the following DGroups:
DG1
DG9
DG12
Here is the code I tried
Foreach($input in $file){
#I’ve tried the split and I get too much data after roles
write-host $input.split(':')[1]
#replace gives me too much info after roles
$input.replace('Please remove the following Roles:','')
#this loop will continuously run
do{
$input}
until{$input.contains("please*")}
}
I expect the output to give me Role1 and Role2, then groups1 and groups2, then profiles1 and profiles3 and profiles8, then dg1 and dg9 and dg12 then ignore the rest.
The issue I am having is in the do loop, I get continuous looping. In the replace, I get the roles but I also get the please remove groups line.
解决方案
[编辑由于示例数据变化很大,以前的代码不起作用。]
它能做什么 ...
- 伪造将文本文件读取为单个多行字符串
- 在空行处将该多行字符串分成块
- 遍历这些块
- 在行尾分割块
- 从第一行获取类型名称
- 从剩余的行中获取项目并将它们存储在一个数组中
- 构建一个
[PSCustomObject]
包含目标类型和项目列表的 - 将其发送到
$Results
集合 - 获取
可以用Roles
其他类型之一替换的目标类型之一的项目 -Groups
就是这样一种。 - 显示整个
$Results
集合内容
,如果需要,该数组可以整齐地导出到 CSV。
编码 ...
# fake reading in a text file as one multiline string
# in real life, use Get-Content -Raw
$InStuff = @'
Please remove the following Roles:
Role1
Role2
Please remove the following Groups:
Groups1
Groups2
Please remove the following Profiles:
Profiles1
Profiles3
Profiles8
Please remove the following DGroups:
DG1
DG9
DG12
'@
$Results = foreach ($Block in $InStuff -split "`r`n`r`n|`r`r|`n`n")
{
$SplitBlock = $Block -split "`r`n|`r|`n"
$BlockName = $SplitBlock[0].Split(' ')[-1].Trim(':')
$ItemList = $SplitBlock[1..$SplitBlock.GetUpperBound(0)]
[PSCustomObject]@{
TargetType = $BlockName
TargetList = $ItemList
}
}
$Results.Where({$_.TargetType -eq 'Roles'}).TargetList
'=' * 30
$Results
输出 ...
TargetType TargetList
---------- ----------
Roles {Role1, Role2}
Groups {Groups1, Groups2}
Profiles {Profiles1, Profiles3, Profiles8}
DGroups {DG1, DG9, DG12}
推荐阅读
- c# - 嵌套列表/循环依赖的不完整映射
- reactjs - React TypeScript:自定义钩子无限循环
- sql-server - 按层次顺序排序表
- ansible - 如何重命名一个ansible角色名称?
- json - 如何使用 System.Text.Json 处理可为空的引用类型?
- cplex - CPLEX:内存不足
- spring - 根据spring boot中另一个@schedule方法的完成触发@schedule
- swift - NSPopUpButton - 使用 Cocoa 绑定填充动态内容时的奇怪行为
- sql - 填充每个类别的值列表
- vba - 错误时来自 GetAttr 的意外 TRUE 返回值