我在终端服务器中由查询 session 命令组成的数组中搜索索引时遇到问题。
这是有问题的脚本:
# Array of logged users in terminal servers
$a=Get-RDUsersession -CollectionName "BLABLA" -ConnectionBroker BLABLA.BLA.BL
# Array of all users with two columns from active directory
$b=Get-ADUser -filter * -properties TelephoneNumber,SamAccountName
现在想象一下使用帐户名 TEST
而不是 test
登录终端服务器。
如果我这样做:
$c = $b[$b.SamAccountName.indexof("test")].TelephoneNumber
然后我没有得到电话号码。
我认为这是因为区分大小写,不是吗?如果我在搜索命令中键入 TEST
,我会得到正确的数字。
有什么简单的方法可以解决这个问题,让索引的搜索不区分大小写吗?
我读过有关使用方法 [StringComparison]"CurrentCultureIgnoreCase"
的信息,但它似乎不适用于数组。
谢谢。
最佳答案
既然 $b 是一个 Object[] 类型,那么你可能想要做一个 Where-Object。
$b | Where-Object -FilterScript {$_.Samaccountname -like '*Smith*'} | Select-Object -ExpandProperty 'telephoneNumber'
也就是说,如果将 Powershell 中的数组转换为 [Collections.Generic.List[Object]] 类型,则可以不区分大小写地对其进行索引。
$b = [Collections.Generic.List[Object]]$b
$b.FindIndex( {$args[0].sAMAccountName -eq 'test'} )
请注意,拉取 AD 中的每个用户对象并使用 where-object 或索引匹配进行过滤可能会非常慢。您可以改为根据需要获取 ADUser,或者使用仅提取 $a 中返回的用户的过滤器提取所有 ADuser。
如果您坚持将所有 ADUser 都集中在一个位置,请考虑循环遍历列表一次以进行散列查找,以便您可以轻松地索引散列值。
#Create account lookup hash
$accountlookup = @{}
foreach ($element in $accounts) {
$accountlookup[$element.SamAccountName] = $element
}
希望对您有所帮助!
关于arrays - 是否可以在 PowerShell 中使 IndexOf 不区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265128/