Powershell 在字符串之间选择文本
我试图在输出字符串之间解析一些文本 我尝试过使用-split和substring,但没有得到正确的输出 以下是输入文件/管道值Powershell 在字符串之间选择文本,powershell,Powershell,我试图在输出字符串之间解析一些文本 我尝试过使用-split和substring,但没有得到正确的输出 以下是输入文件/管道值 Please remove the following Roles: Role1 Role2 Please remove the following Groups: Groups1 Groups2 Please remove the following Profiles: Profiles1 Profiles3 Profiles8 Please remove th
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
这是我试过的代码
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*")}
}
我希望输出给我Role1和Role2,然后是groups1和groups2,然后是profiles1和profiles3和profiles8,然后是dg1、dg9和dg12,然后忽略其余部分
我遇到的问题是在do循环中,我得到了连续循环。
在replace中,我得到了角色,但也得到了请删除组行 [编辑,因为示例数据变化太大,以前的代码无法工作。]
它的作用
- 伪造将文本文件作为单个多行字符串读取
- 将多行字符串在空白行 中分块
- 通过这些块进行迭代
- 在线端拆分块
- 从第1行获取类型名称
- 从其余行获取项并将其存储在数组中
- 构建一个
来保存目标类型和项目列表[PSCustomObject]
- 将其发送到
集合$Results
- 获取其中一个目标类型的项
您可以将
替换为其他类型之一-角色
就是这样一种类型李>组
- 显示整个
集合内容$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}
$file-替换“+(?=角色:|组:|配置文件:| DGroups:)”您面临的错误是什么?你有没有试过别的方法?可能有多种方法可以实现这一点。包含管道值的文件看起来怎么样?请更新您的问题,以显示您已经尝试过的内容,并在一个最小、完整且可验证的示例中显示您面临的具体问题。有关更多信息,请参见如何提出一个好问题(),并参观网站(),文件的开头是
还是结束输入文件
?如果没有,请将其移除。此外,请使用代码格式设置示例数据的格式,以使其正确显示。我已更新example@DonB-不客气!很高兴能帮上一点忙。。。[grin]如何返回groups1和groups2的值?我试着将比赛调整到小组赛,但我仍然得到了角色1和角色2role2@DonB-让我玩一下修改后的数据示例,看看如何获取所有数据sets@DonB-看看新版本。。。[咧嘴笑]正是我需要的。令人惊叹的“+(?=Roles:| Groups:| Profiles:| DGroups:)”到底做什么?很好。这也行得通。我只需要解析那个输出,就可以一次得到我需要的每个部分。