Fr33c3l
Fr33c3l

Reputation: 165

Function inside Where-Object clause

I am trying to find AD users by name and surname but with converted non-english diacritics to english signs

Ex. convert Ł to L etc.

So I wrote:

Get-ADUser -Filter * -Properties GivenName, Surname | Where-Object {
  [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes($_.GivenName)) -eq $name
}

It's working fine, but I am getting an error:

Exception calling "GetBytes" with "1" argument(s): "Array cannot be null."

Does Powershell not like function inside where clause?

Upvotes: 2

Views: 1573

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

If an AD user doesn't have a set GivenName attribute, or if you forgot to retrieve it by specifying -Properties GivenName in your AD cmdlet call, $_.GivenName will evaluate to $null.

[Encoding]::GetBytes() has a number of overloads:

byte[] GetBytes(char[] chars)
byte[] GetBytes(char[] chars, int index, int count)
byte[] GetBytes(string s)

When you pass a $null value, the .NET runtime cannot figure out whether $null represents an empty string, and chooses the overload that takes a char[] instead, resulting in the Array cannot be null error.

Enclose $_.GivenName in double quotes, to force it to be recognized as a string, eliminating any ambiguity:

[Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes("{0}" -f $_.GivenName))
# or 
[Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes("$($_.GivenName)"))

This way, if $_.GivenName evaluates to $null, you'll just be passing an empty string to GetBytes(), which is perfectly valid

Upvotes: 2

Related Questions