PowerShell按'-'分割含roleReferences配置的字符串获取数组问题咨询
问题原因
你直接用-分割字符串会把内容里所有的横杠都作为分隔符,且无法区分普通横杠和roleReferences下作为条目开头的行首横杠,同时会把前面的异常信息、元数据和末尾的OK也混入结果。
正确实现步骤
1. 先截取有效内容区间
先过滤掉roleReferences:之前的冗余内容和末尾的OK标识,只保留角色条目部分:
# 定位有效内容的起止位置 $startPos = $string.IndexOf("roleReferences:") + "roleReferences:".Length $endPos = $string.LastIndexOf("`nOK") $roleRawContent = $string.Substring($startPos, $endPos - $startPos).Trim()
2. 按行首横杠分割条目
用PowerShell正则分割的多行模式,仅匹配行首的横杠作为分隔符,同时过滤空值、清理多余空白:
# (?m)开启多行模式,^匹配每行行首,仅分割作为条目开头的横杠 $Myarray = $roleRawContent -split '(?m)^\-\s?' | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | ForEach-Object { $_.Trim() }
结果验证
输出$Myarray会得到两个元素,分别对应两个角色条目:
- 第一个元素内容:
roleTemplateAppId: it!b2455 roleTemplateName: AuthGroup_Administrator name: AuthGroup_Administrator
- 第二个元素内容:
roleTemplateAppId: it!b2455 roleTemplateName: AuthGroup_BusinessExpert name: AuthGroup_BusinessExpert
内容的提问来源于stack exchange,提问作者Lord OfTheRing
相关产品推荐
相关产品推荐

