Is it possible to make IndexOf case-insensitive in PowerShell?

Viewed 2294

I've got a problem searching an INDEX in an array made up by query sessions command in a terminal server.

This is the problematic script:

# 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

Now imagine logging in the terminal server using the account name TEST instead of test.

If I do:

$c = $b[$b.SamAccountName.indexof("test")].TelephoneNumber

then I don't get the telephone number.

I think that's because of the case sensitivity, isn't it? If I type TEST in the search command, I get the correct number.

Is there any simple way to solve this problem and make the search of the index case-insensitive? I've read about using the method [StringComparison]"CurrentCultureIgnoreCase", but it seems not working with array.

Thanks.

1 Answers

Since $b is an Object[] type, then you would probably want to do a Where-Object.

$b | Where-Object -FilterScript {$_.Samaccountname -like '*Smith*'} | Select-Object -ExpandProperty 'telephoneNumber'

That being said, an array in Powershell can be indexed case-insensitively if it is converted to a [Collections.Generic.List[Object]] type.

$b = [Collections.Generic.List[Object]]$b
$b.FindIndex( {$args[0].sAMAccountName -eq 'test'} )

Note that pulling every single user object in AD and filtering using where-object or index matching can be very slow. You can instead Get-ADUser as needed or pull all ADusers using a filter that pulls only the users returned in $a.

If you insist on having all ADUsers in one spot with one pull, consider looping over the list once to make a hash lookup so you can easily index the hash value.

#Create account lookup hash
$accountlookup = @{}
foreach ($element in $accounts) {
  $accountlookup[$element.SamAccountName] = $element 
}

Hope that helps!

Related