且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

String.Split() 的奇怪结果

更新时间:2023-02-04 22:36:45

它为分隔符中的每个字符拆分字符串.所以它把它分成'O','U' &'='.

It splits the string for each character in the separator. So its splitting it on 'O', 'U' & '='.

正如@mklement0 所评论的,我之前的回答并不适用于所有情况.因此,这是获取预期项目的另一种方法.

As @mklement0 has commented, my earlier answer would not work in all cases. So here is an alternate way to get the expected items.

$a.Split(',') |% { $_.Split('=') |? { $_ -ne 'OU' } }

此代码将拆分字符串,首先在 上拆分,然后在 = 上拆分每个项目并忽略 OU 的项目,最终返回预期值:

This code will split the string, first on , then each item will be split on = and ignore the items that are OU, eventually returning the expected values:

RAH
RAC

即使在以下情况下也能工作:

This will work even in case of:

$a = 'OU=FOO,OU=RAH,OU=RAC'

生成 3 个项目 FOO, RAH &RAC

generating 3 items FOO, RAH & RAC

要按预期仅获得 2 个字符串,您可以使用以下行:$a.Split('OU=', [System.StringSplitOptions]::RemoveEmptyEntries)这将使输出为:拉赫,RAC如果您使用(注意分隔符中的逗号)$a.Split(',OU=', [System.StringSplitOptions]::RemoveEmptyEntries)你会得到RAHRAC

这可能就是你想要的.:)

This is probably what you want. :)