powershellcsvactive-directoryou

Compare AD users from CSV to a specific OU


I have a CSV list of usernames from all over my domain, and I'm trying to compare the list against a specific OU and send the matches to another file. I'm brand new to powershell, so after a good amount of research and comparing with other scripts I came up with this:

$users = Import-csv C:\Users\me\Desktop\'RSA.csv' 
$(ForEach ($user in $users) 
{
Get-AdUser -identity $user -SearchBase "ou=Sub,ou=Root,dc=My,dc=Domain,dc=Name" -Filter * 
}) |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation 

When I run this I get the error "Get-ADUser : Cannot validate argument on parameter 'Identity'. The Identity property on the argument is null or empty." If I run without the -identity $user it just pulls everything. Any suggestions on how to make this work?


Solution

  • When you are calling Get-ADUser rather than giving it a string with just the user name you are passing in an object with a property called username. You could use Select-Object -ExpandProperty Username or reference the just property.

    Import-Csv 'C:\Users\me\Desktop\RSA.csv' | 
        Where-Object {(!([string]::IsNullorWhiteSpace($_.UserName)))} |
        ForEach-Object {
            Get-ADUser -Identity $_.UserName
        } |
        Select-Object SamAccountName |
        Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation 
    

    Notes: Changed to a ForEach-Object loop for readability since it looked like you where trying to mostly use the pipeline. Also added a test to skip blank lines or usernames that are whitespace/empty string. Removed the SearchBase and Filter since you are looking up based on identity can't use those in the command. As there isn't a parameter set that allows you to use all of them. Get-Help Get-ADUser shows the available parameter sets.