0

Goal: Trying to search AD against a CSV file with powershell that contains a listing of SamAccountNames. In some cases the SamAccountNames are similar or already in the database and I I want to avoid attempting to create an account that is already in AD. so I need to be able to check first with the -like samaccountname* [notice I need the wildcard]. I can successfully run this command and get the expected results for one user. What I can't get to work is importing from a CSV file so I don't have to do this search manually for 100 people.

Powershell code: Get-aduser -filter "SamAccountName -like 'DoeJim*" -Properties * | Format-table SurName,GivenName, Initials,SamAccountName,UserPrincipalName,Name

So the above command works great for one user search, exactly the output and results I want/need to see, but unable to incorporate the import-csv with the foreach or foreach-object, can't seem to get the correct combination of code. below is what I came up with and does not work Import-Csv 'c:\import.csv' | foreach {get-aduser -filter samAccountName -like $_."SamAccountName*" -Properties *} | Select SurName,GivenName,Initials,SamAccountName,UserPrincipalName,Name

Error: When I run the powershell command, i get the following error: Get-AdUser : A parameter cannot be found that matches parameter name 'like'. At line:1 char:154 +...port.csv' | foreach {Get-ADUser -filter SamAccountName -like $_."Sam ...

If someone can provide some hints or guidance as to what I am clearly doing wrong or missing would be greatly appreciated.

1 Answer 1

1

If Get-ADUser -Filter {sAMAccountName -like "DoeJim*"} works then the following code snippet gives exactly the same results

Import-Csv 'c:\import.csv' |
    ForEach-Object {
        Get-ADUser -filter {sAMAccountName -like "$($_.SamAccountName)*"}
    }

Here is used Subexpression operator $( ):

Returns the result of one or more statements. For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression.

Note. Used the -Filter syntax pattern from PowerShell: Filter Results with Active Directory Module Cmdlets article.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.