I'm somewhat basic to Powershell and use one-liner commands only to keep it short and basic.
I would like to do the following: I have a list of users in a text file in the form of UserPrincipalName
. I'd like to query this list of users if their accounts are still active/enabled or not. To do so, I'm trying to run the following command, which just reveals nothing in the end (blank output):
gc .\users.txt | foreach {get-aduser -server "corp.xxx.com"
-f 'name -like "$_"' -properties *}| select displayname,enabled
As mentioned, the output is blank with no errors or whatsoever. I read that aduser doesn't work with pipelines, but I need to find a solution.
Kindly request your support :)
Thanks
CodePudding user response:
Your use of single quotes in your filter is not allowing the expansion of the variable. Double-quotes should be wrapping the filter expression so as to allow the interpolation of the automatic variable $_
:
Get-ADUser -Filter "name -like '$_'" ...
A string enclosed in single quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed.
Also note, you mention in your question that the file has the user's UserPrincipalName
attribute, yet you're querying the Name
attribute, if that's the case, the filter should be:
Get-ADUser -Filter "UserPrincipalName -eq '$_'" ...
Note the use of -eq
instead of -like
, for exact matches you should always use this operator, see about_ActiveDirectory_Filter for usage details and examples of each operator.
If you're only interested in DisplayName
and Enabled
for your output, there is no reason in querying all the user's attributes, -Properties *
should be just -Properties DisplayName
since Enabled
is already part of the default attributes returned by Get-ADUser
.
Finally, the -Identity
parameter can be bound from pipeline, and this parameter accepts a UserPrincipalName
as argument, hence ForEach-Object
is not needed in this case:
Get-Content .\users.txt |
Get-ADUser -server "corp.xxx.com" -Properties DisplayName |
Select-Object DisplayName, Enabled