The answers by Gabriel Luci and Mathias R. Jessen give good advice on "fuzzy" filtering of AD users.[1]
However, your primary problem is that your ForEach-Object
call is not receiving pipeline input, because you haven't connected it to output from the Import-Csv
call.
Secondarily, your -Filter
argument { Name -like "'$($_.name)'"}
mistakenly applies two layers of quoting and is missing wildcard characters, given that -like
compares against the entire field, yet you want substring matching.
Since it's better to avoid the use of script blocks ({ ... }
) as -Filter
arguments, use a string:
"Name -like `"*$($_.name)*`"" # Note the enclosing '*' to match substrings
Note that I've used embedded "
quoting (escaped as `"
) rather than '
quoting, so as not to break the filter with names that contain '
, such as O'Malley
.
That said, if, as your question suggests, the names in your CSV data aren't direct substrings of the AD users' .Name
property values, the above filter will not be enough, and even the ANR (Ambiguous Name Resolution) technique shown in the linked answers may not be enough.
Thirdly, your Export-Csv
call is misplaced: because it is inside the ForEach-Object
script block, the same output file gets overwritten in every iteration.
Optional reading: ForEach-Object
behavior when not providing pipeline input:
The associated script block is executed once.
$_
, the automatic variable that contains the current input object, is $null
.
[1] Note that the search term in the LDAP filter may need escaping ; per this article, the characters * ( ) \ NUL
require escaping and must be escaped as \<hh>
, where <hh>
is the two-digit hex representation of the char's ASCII code (e.g., *
must be escaped as \2A
):
$escapedName = -join $(foreach ($c in [char[]] $_.name) { if ('*', '\', '(', ')', "`0" -contains $c) { '\' + ([int] $c).ToString('X2') } else { $c } })
Get-ADUser -LDAPFilter "(anr=$escapedName)"
With $_.name
containing string "James* (Jimmy) Smith\Smyth`0"
, $escapedName
would evaluate to literal James\2A \28Jimmy\29 Smith\5CSmyth\00